需求背景:文章详情页,上面部分为 H5,中间为推荐内容,最下面为评论列表
对于这种需求,其实最好的办法就是,整个页面全部是 H5 做好的模板,然后通过 Android 和 WebView 交互去填充数据。
可是事与愿违,为了节约开发和对接成本,竟要求用 WebView + 原生界面 混合套在 滑动布局里,只有文章部分用 H5… 咱也没办法呀!
NestedScrollView 或 ScrollView 等滑动布局嵌套 WebView 时(虽然 Google 并不推荐这么做,但是万恶的产品可不管这些东西,狗头保命)通常会导致 H5 部分的高度不能自适应,要么加载显示不全,要么底部会多出非常多的空白。网上看了一圈也没有合适的解决方案,那咱就自己撸起袖子干。
解决思路:轮询获取 H5 的高度,然后重置 WebView 的高度
原理很简单吧,往往复杂的事解决起来也没有想象的那么麻烦。
- 自定义一个 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()
...
}
}
- 创建一个重置 WebView 高度的方法
...
/**
* 重置 WebView 高度
*/
private fun resetHeight(contentHeight: Int) = updateLayoutParams {
height = contentHeight
}
...
- 创建一个轮询获取 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
}
- 创建开启和关闭的方法
...
/**
* 高度监控实时回调,重置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()
}
...
完整的代码:
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()
避免内存泄漏。
原创声明:未经本人许可,禁止转载!!!