[英]Jetpack Compose WebView Handling Back Navigation And Go To Previous Page
I am using Jetpack Compose and have a WebView
wrapped in a AndroidView
composable that looks like the following:我正在使用 Jetpack Compose,并有一个
WebView
包装在一个AndroidView
可组合组件中,如下所示:
AndroidView(modifier = modifier, factory = { context ->
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = WebViewClient()
settings.javaScriptEnabled = true
}
}, update = { webView -> webView.loadUrl(url) })
In the legacy way, we could add a OnBackPressedDispatcher
to the Activity
to intercept the back press and navigate inside the WebView
by accessing it via viewBinding for example with functions of the WebView
like goBack()
and to check if you can go back with canGoBack()
. In the legacy way, we could add a
OnBackPressedDispatcher
to the Activity
to intercept the back press and navigate inside the WebView
by accessing it via viewBinding for example with functions of the WebView
like goBack()
and to check if you can go back with canGoBack()
.
But how can we achieve the same with this Jetpack Compose approach?但是我们如何使用这种 Jetpack Compose 方法实现相同的目标呢?
There doesn't seem to be anything wrong with assigning the WebView to an external var so that's what I've done here.将 WebView 分配给外部变量似乎没有任何问题,所以这就是我在这里所做的。
var backEnabled by remember { mutableStateOf(false) }
var webView: WebView? = null
AndroidView(
modifier = modifier,
factory = { context ->
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
backEnabled = view.canGoBack()
}
}
settings.javaScriptEnabled = true
loadUrl(url)
webView = this
}
}, update = {
webView = it
})
BackHandler(enabled = backEnabled) {
webView?.goBack()
}
The WebViewClient
listens for onPageStarted
which checks if the WebView can navigate backwards and then updates backEnabled
. WebViewClient
侦听onPageStarted
,它检查 WebView 是否可以向后导航,然后更新backEnabled
。 This causes a recomposition which toggles the BackHandler on and off.这会导致重新组合打开和关闭BackHandler 。
I've also moved loadUrl
out of the update
function and into factory
because update is called every time there's a recomposition whereas factory is only called the once.我还将
loadUrl
从update
function 中移出并移至factory
,因为每次重组时都会调用更新,而工厂只调用一次。 This may or may not be relevant based on your implementation.根据您的实施,这可能相关也可能不相关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.