从性能的角度来说,在ScrollView中是不建议嵌套WebView的,该说明在官方文档中也有所说明。但是总会有些无聊的需求导致不得不使用该种方法来实现功能。那么问题来了,将WebView放在ScrollView中,运行时在WebView的底部经常会出现一大片的空白。终究原因还是适配的问题。下面小编将详细的介绍解决方案。
方案一、设置ScrollView属性
android:fillViewport="true"
方案二、禁用缩放等属性
wv.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
wv.setVerticalScrollBarEnabled(false);
wv.setVerticalScrollbarOverlay(false);
wv.setHorizontalScrollBarEnabled(false);
wv.setHorizontalScrollbarOverlay(false);
如若将WebView的横向与竖向的ScrollBar都禁用,将不再与ScrollView冲突,解决大面积空白的问题。
int screenDensity =getResources().getDisplayMetrics().densityDpi ;
WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
switch (screenDensity){
case DisplayMetrics.DENSITY_LOW :
zoomDensity = WebSettings.ZoomDensity.CLOSE;
break;
case DisplayMetrics.DENSITY_MEDIUM:
zoomDensity = WebSettings.ZoomDensity.MEDIUM;
break;
case DisplayMetrics.DENSITY_HIGH:
zoomDensity = WebSettings.ZoomDensity.FAR;
break ;
}
settings.setDefaultZoom(zoomDensity);
方案三、JS注入
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
mWebView.loadUrl("javascript:App.resize(document.body.getBoundingClientRect().height)");
super.onPageFinished(view, url);
}
});
mWebView.addJavascriptInterface(this, "App");
@JavascriptInterface
public void resize(final float height) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//Toast.makeText(getActivity(), height + "", Toast.LENGTH_LONG).show();
mWebView.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));
}
});
}
方案四、设置属性
this.getSettings().setLoadWithOverviewMode(true);
this.getSettings().setUseWideViewPort(true);
this.getSettings().setBuiltInZoomControls(true);
Write by Jimmy.li