Android NestedScrollView 等滑动布局嵌套 WebView 导致页面高度不全或大段空白问题的最完美解决方案

需求背景:文章详情页,上面部分为 H5,中间为推荐内容,最下面为评论列表

对于这种需求,其实最好的办法就是,整个页面全部是 H5 做好的模板,然后通过 Android 和 WebView 交互去填充数据。

可是事与愿违,为了节约开发和对接成本,竟要求用 WebView + 原生界面 混合套在 滑动布局里,只有文章部分用 H5… 咱也没办法呀!

NestedScrollView 或 ScrollView 等滑动布局嵌套 WebView 时(虽然 Google 并不推荐这么做,但是万恶的产品可不管这些东西,狗头保命)通常会导致 H5 部分的高度不能自适应,要么加载显示不全,要么底部会多出非常多的空白。网上看了一圈也没有合适的解决方案,那咱就自己撸起袖子干。

解决思路:轮询获取 H5 的高度,然后重置 WebView 的高度

原理很简单吧,往往复杂的事解决起来也没有想象的那么麻烦。

  1. 自定义一个 WrapWebView
class WrapWebView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : WebView(context, attrs, defStyleAttr) {

    init {
        settings.also {
            it.javaScriptEnabled = true
            it.allowFileAccess = true
        }
        webChromeClient = WebChromeClient()

        webViewClient = WebViewClient()
        
        ...
    }
}
  1. 创建一个重置 WebView 高度的方法
	...
	
    /**
     * 重置 WebView 高度
     */
    private fun resetHeight(contentHeight: Int) = updateLayoutParams {
        height = contentHeight
    }
    
    ...
    
  1. 创建一个轮询获取 H5 内容高度的任务
	...
	
    /**
     * 是否正在轮询
     */
    private val isMonitoring = false

    /**
     * 记录上次 H5 的高度
     */
    private var webHeight = -1

    /**
     * 获取 H5 高度,需要在 onPageFinished 后调用
     */
    private val resetHeightTask: Runnable = object : Runnable {
        override fun run() {
            if (!isMonitoring || !isAttachedToWindow) {
                return
            }
            // 获取 H5 body 高度。当然轮询也可以在 H5 那边实现然后回调给原生
            evaluateJavascript(
                "document.getElementsByTagName('body')[0].offsetHeight"
            ) { value: String ->
                try {
                    // 计算真实高度,回调的高度需要乘以 WebView 的缩放比
                    val contentHeight = (value.toInt() * scale).toInt() + 100
                    if (webHeight != contentHeight && contentHeight > 0) {
                        // 重置高度
                        webHeight = contentHeight
                        resetHeight(webHeight)
                    }
                    postDelayed(this, TASK_DELAY)
                } catch (e: Exception) {
                    postDelayed(this, TASK_DELAY)
                }
            }
        }
    }
    
    ...
    
	companion object {
	
        /**
         * 轮询间隔 200 ms
         */
        const val TASK_DELAY: Long = 200

    }
    
  1. 创建开启和关闭的方法
	...
	
    /**
     * 高度监控实时回调,重置WebView高度
     */
    fun startMonitor() {
        isMonitoring = true
        postDelayed(resetHeightTask, TASK_DELAY)
    }

    fun stopMonitor() {
        isMonitoring = false
        removeCallbacks(resetHeightTask)
    }

	...
	
  1. 销毁方法重写
	...
	
    override fun destroy() {
        stopMonitor()
        loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        clearHistory()
        super.destroy()
    }
    
    ...
    

完整的代码:

package xxx

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.view.updateLayoutParams

/**
 * WrapWebView
 *
 * @author why
 * @since 2021/7/22
 */
@SuppressLint("SetJavaScriptEnabled")
class WrapWebView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : WebView(context, attrs, defStyleAttr) {

    /**
     * 是否正在轮询
     */
    private var isMonitoring = false

    /**
     * 记录上次 H5 的高度
     */
    private var webHeight = -1

    /**
     * 获取 H5 高度,需要在 onPageFinished 后调用
     */
    private val resetHeightTask: Runnable = object : Runnable {
        override fun run() {
            if (!isMonitoring || !isAttachedToWindow) {
                return
            }
            // 获取 H5 body 高度。当然轮询也可以在 H5 那边实现然后回调给原生
            evaluateJavascript(
                "document.getElementsByTagName('body')[0].offsetHeight"
            ) { value: String ->
                try {
                    // 计算真实高度,回调的高度需要乘以WebView 的缩放比
                    val contentHeight = (value.toInt() * scale).toInt() + 100
                    if (webHeight != contentHeight && contentHeight > 0) {
                        // 重置高度
                        webHeight = contentHeight
                        resetHeight(webHeight)
                    }
                    postDelayed(this, TASK_DELAY)
                } catch (e: Exception) {
                    postDelayed(this, TASK_DELAY)
                }
            }
        }
    }

    init {
        settings.also {
            it.javaScriptEnabled = true
            it.allowFileAccess = true
        }
        webChromeClient = WebChromeClient()

        webViewClient = WebViewClient()
    }

    /**
     * 重置 WebView 高度
     */
    private fun resetHeight(contentHeight: Int) = updateLayoutParams {
        height = contentHeight
    }


    /**
     * 高度监控实时回调,重置WebView高度
     */
    fun startMonitor() {
        isMonitoring = true
        postDelayed(resetHeightTask, TASK_DELAY)
    }

    fun stopMonitor() {
        isMonitoring = false
        removeCallbacks(resetHeightTask)
    }

    override fun destroy() {
        stopMonitor()
        loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        clearHistory()
        super.destroy()
    }

    companion object {
        /**
         * 轮询间隔 200 ms
         */
        const val TASK_DELAY: Long = 200

    }
}

使用方法:
在页面中初始化 WrapView,然后在webview.loadUrl("xxx")之后调用 webview.startMonitor()即可在滚动布局中自动适配 H5 高度,还可以继续在滚动布局中嵌套其他原生控件了。

其实 Android WebView 有提供获取内容高度的方法:val height = contentHeight * scale,但是这个值部分界面是正常的,很多时候这个高度都不能用,还是自己老老实实轮询获取高度稳妥。

注意:
在Activity 销毁时,记得调用webview.destroy()避免内存泄漏。

原创声明:未经本人许可,禁止转载!!!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值