本文介紹了Webview與ScrollView的滾動兼容及留白處理,分享給大家,具體如下:
背景
開發中我們經常會遇到使用網頁來顯示圖文內容,而且往往我們會遇到webview嵌套在scrollview的這種情況,這就開始讓人蛋疼了!“為嘛,我的webview加載出來的網頁只顯示很小一點,其他都不顯示了?” ”當我重新刷新頁面后,為什么webview會出現留白的情況?“ ----------------- 天啊,難道就不能好好的嗎?!
為了解決項目中這些蛋疼的問題,試過不少方法,網上有說是網頁中使用了不合理的overflow,的確,經證實使用不合理的overflow的確會造成網頁加載后在嵌套在scrollview的webview只會顯示很小的高度,那體驗是相當的尷尬。合理使用overflow即可處理這個問題,但是webview留白又如何處理呢?問題先放這兒,我們先說說如何在xml布局中放置webview并設置他的屬性。
層層遞進,先練基本功
xml中webview嵌套在scrollview中:
<ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:descendantFocusability="blocksDescendants" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <com.xxxx.NoWrapListView android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"/> <WebView android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout></ScrollView>
其中webview要的高度要設置為:wrap_content, 如有必要可設置scrollview第一個子容器的這個屬性:
android:descendantFocusability="blocksDescendants"
發現問題,問題是如何造成的
我們使用webview加載網頁,網頁可能在我們需要的時候會要求我們刷新網頁或者加載新的鏈接,這時候問題就顯現了。由于網頁頁面加載內容的長度,或者ajax請求延遲,造成webview只能不斷的增加高度,而當網頁高度變小時,webview高度卻不能自適應了,那么只能由我們手動的搞些事情了!
解決問題,解決留白,刻不容緩
1、重載WebViewClient,重寫onPageFinished方法。
inner class XWalkWebClient : WebViewClient() { override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {  super.onPageStarted(view, url, favicon)  isPageLoadSuccess = true } override fun onPageFinished(view: WebView?, url: String?) {  super.onPageFinished(view, url)  view?.loadUrl("javascript:window.myapp.resize(document.body.getBoundingClientRect().bottom);") //此處調用了一個注入的js方法用來重載webview高度,可解決初始加載網頁的問題,① }}2、js注入,初始化注入方法
webBrowser?.addJavascriptInterface(MyAppJavascriptHandler(), "myapp")
inner class MyAppJavascriptHandler { @JavascriptInterface    fun resize(documentBodyHeight: Int) {      if (isAllowReLayoutBrowser) {        (context as? Activity?)?.runOnUiThread {          ViewUtil.setViewLayoutParams<FrameLayout.LayoutParams>(webBrowser!!, {            it.width = context.resources.displayMetrics.widthPixels            it.height = (documentBodyHeight * context.resources.displayMetrics.density).toInt()          }) //重寫webview的高度, ②        }      }    }}網頁端也需要在數據加載完成后調用這個js注入方法
if(window.myapp.resize){ window.myapp.resize(document.body.getBoundingClientRect().bottom);}備注、解釋:
①. document.body.getBoundingClientRect().bottom: 網頁下邊距離頁面上邊的距離
②. ViewUtil.setViewLayoutParams....方法的實現
/** * 配置控件的布局屬性 * @param view * @param func 處理布局屬性的回調方法 */@Suppress("unchecked_cast")@JvmStaticfun <T : ViewGroup.LayoutParams> setViewLayoutParams(view: View, func: (T) -> Unit) = with(this) { val lp: T = view.layoutParams as T func.invoke(lp) view.layoutParams = lp}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答