Android ScrollView嵌套WebView出現大面積空白頁解決方法


    從性能的角度來說,在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);





Good luck!

Write by Jimmy.li





 

 


發佈了74 篇原創文章 · 獲贊 76 · 訪問量 71萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章