Android get height of webview content once rendered

后端 未结 5 1417
忘了有多久
忘了有多久 2020-12-14 18:44

I\'m trying to get the height of a webview once it has been rendered. It always returns null, I\'ve tried getHeight, getMeasuredHeight, getCo

5条回答
  •  星月不相逢
    2020-12-14 19:20

    I found this solution to be 100% reliable.

    Subclass your WebView and there is a need to invoke javascript after the content has been loaded.

    // callback made this way in order to get reliable html height and to avoid race conditions
        @SuppressLint("SetJavaScriptEnabled")
        override fun onPageFinished(view: WebView?, url: String?) {
            view?.let {
                it.settings.javaScriptEnabled = true
                it.addJavascriptInterface(WebAppInterface(it), "AndroidGetHeightFunction")
                it.loadUrl("javascript:AndroidGetHeightFunction.resize(document.body.scrollHeight)")
            }
        }
    

    We can then get proper height and disable javascript in callback (for security and consistency):

    inner class WebAppInterface(private val webView: WebView) {
        @JavascriptInterface
        fun resize(height: Float) {
            webView.post {
                heightMeasuredListener?.invoke(formatContentHeight(webView, height.toInt()))
                webView.settings.javaScriptEnabled = false
            }
        }
    }
    

    WebView must call post() as the code inside resize(...) is called in WebView thread!

    After, make sure to scale your pixels to match density pixels!:

    fun formatContentHeight(webView: WebView, height: Int): Int = Math.floor((height * webView.context.resources.displayMetrics.density).toDouble()).toInt()
    

提交回复
热议问题