安卓開發——WebView+Recyclerview文章詳情頁,解決高度問題


安卓開發——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下載

文章詳情 Demo下載

參考

文中的WebView以及NestedScroll的用法參考:10分鍾帶你入門NestedScrolling機制 - SegmentFault 思否

其他實現方案:上面webview 下邊評論 (applemei.com)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM