不规范使用webview导致白屏

435 阅读1分钟

本打算使用webView 在compose中使用,并且复用,可是在如下代码中,会发生黑屏的问题

viewModel中持有webView控件对象

class GlobalViewModel(application: Application) : AndroidViewModel(application) {
    @SuppressLint("StaticFieldLeak")
    var webViewX5: com.tencent.smtt.sdk.WebView? = null
    val webView= MutableStateFlow<com.tencent.smtt.sdk.WebView?> (null)
}

在topLevel中初始化

@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun WebBrowserPostX5(
    modifier: Modifier = Modifier,
    url: String,
    backEnabled: Boolean = true,
    onBack: (webView: WebView?) -> Unit = {},
    onProgressChange: (progress: Int) -> Unit = {},
    initSettings: (webSettings: WebSettings) -> Unit = {},
    onReceivedError: (webView: WebView, error: WebResourceError?) -> Unit = { _: WebView, _: WebResourceError? -> },
    viewModel: GlobalViewModel? = null,
    postData: ByteArray = ByteArray(0),
) {
   ...
    AndroidView(modifier = modifier, factory = { context ->
        //优先复用以前的
        /*viewModel?.webViewX5 ?:*/
       // viewModel?.webView?.value?: 加这句也会白屏,暂时不清楚是什么原因
        WebView(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            this.webViewClient = webViewClient
            this.webChromeClient = webViewChromeClient
            //回调webSettings供调用方设置webSettings的相关配置
            initSettings(this.settings)
            webView = this
            viewModel?.webView?.tryEmit(this)
            postUrl(url, postData)
//                    viewModel?.webViewX5 = this//加这句白屏
        }
    })

    if (backEnabled) {
        BackHandler {
            coroutineScope.launch {
                //自行控制点击了返回按键之后,关闭页面还是返回上一级网页
                onBack(webView)
            }
        }
    }
}