安卓開發——WebView+Recyclerview文章詳情頁,解決高度問題
最近在寫一個APP時,需要顯示文章詳情頁,准備使用WebView和RecyclerView實現上面文章,下面評論。出現了WebView高度問題,WebView加載HTML
格式數據,而非URL
。
-
這里的
WebView
為自定義組件NestedScrollingWebView
,已解決嵌套滑動問題。 -
如果WebView設置為
wrap_content
,會出現下面的評論會在WebView渲染數據時提前顯示在上面的情況,很不美觀 -
如果WebView設置為
match_parent
,當文章高度不足一屏時,下面空白太大,不美觀。
案例
設置為wrap_content
設置為match_parent
設置為match_parent,不另設置高度
通過JS設置高度
解決方案
利用JS
獲取高度,然后通知(loadUrl(js)
)WebView改變高度。關於JS
獲取高度,這里采用了一種我覺得很准確的方法
private fun getHtmlData(title:String, bodyHTML: String): String {
val head = ("<head>" +
"<meta name=\"viewport\" " +
"content=\"width=device-width, " +
"initial-scale=1.0, user-scalable=no\"> " +
"<style></style></head>")
return "<html>$head<body>" +
"<h2 class='title'>$title</h2>$bodyHTML<div class='bottom'></div>" +
"</body></html>"
}
在文章內容的最下面加一個div
,通過document.querySelector('.bottom').offsetTop
來用於確定高度
具體方法
1、先創建一個Mobile
類
private inner class Mobile {
@JavascriptInterface
fun onGetWebContentHeight(height: Int) {
contentWV.post {
val layoutParams = contentWV.layoutParams
layoutParams.height = Utils.getPixelByDp(this@JsSetHeightActivity, height)
contentWV.layoutParams = layoutParams
Log.i(TAG, "onGetWebContentHeight: height=$height")
}
}
}
2、在初始化WebView
時,設置必要參數
private fun initView() {
contentWV = findViewById<NestedScrollingWebView>(R.id.content_wv)
// 開啟js
val setting = contentWV.settings
setting.javaScriptEnabled = true
// 添加JS接口
val mobile = Mobile()
contentWV.addJavascriptInterface(mobile, "mobile")
// 在 onPageFinished時重新設置高度
val webClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
val js = "javascript:mobile.onGetWebContentHeight(document.querySelector('.bottom').offsetTop)"
view?.loadUrl(js)
}
}
contentWV.webViewClient = webClient
}
在頁面加載完成之后,會重新設置高度
Demo下載
參考
文中的WebView
以及NestedScroll
的用法參考:10分鍾帶你入門NestedScrolling機制 - SegmentFault 思否