android - Composable 之间的通信
问题描述
我创建了 WebView,它是可组合的 Android 视图。它是屏幕 Scaffold 的内容,Scaffold 本身具有 TopBar 作为操作栏,左侧有一个后退按钮,我想处理后退按钮的 onClicked 以检查 WebView 是否可以正常返回Android 视图上的行为。问题是如何让 onClicked 事件知道 WebView?
代码:
Scaffold(
topBar = {
CustomAppBar(
title = title,
onBackPressed = {
// check webview.canGoBack()
// if yes, just go back
// if not, finish activity
},
)
},
content = {
CustomWebView(
url = originalUrl,
)
}
)
解决方案
You need to keep track of it in a variable, let's say outside the scaffold. Something like
var canGoBack by mutableStateOf (false)
var goBackTrigger by mutableStateOf (false)
Scaffold(
topBar = {
CustomAppBar(
title = title,
onBackPressed = {
if(canGoBack){
goBackTrigger = true
}
else{
//Finish activity
}
},
)
},
content = {
CustomWebView(
url = originalUrl,
goBackTrigger = goBackTrigger
)
}
)
@Composable
fun CustomWebView(
url: String,
goBackTrigger: Boolean
){
//Add this where you can access the webView methods
if(goBackTrigger){
webView.goBack()
goBackTrigger = false
//You might need to update the url here as well. See to it.
}
}
The idea is to store the state in a variable, and modifying that variable from the content web view whenever the conditions are met. The reason for defining the variable just above scaffold is to ensure that it is accessible from within the content block.
Whenever the trigger changes, the webView gets recomposed since it is reading this variable.
推荐阅读
- linux - 是否可以通过 Linux 中的 /sys 从特定内核获取当前 CPU 利用率?
- python - Python:找到跳出循环的条件
- python - Django - 如何为不同的 XML 格式存储不同的解析技术?
- javascript - 无法读取未定义的“消息”的属性
- node.js - Angular 6,在HttpClient请求后不断返回错误消息“[url here]的Http失败响应:0未知错误”
- material-ui - @material-ui/styles 适配 hook API
- c - 在C中将输入复制到输出而没有不必要的空格
- javascript - FabricJS - 为什么在更新组内的文本后,组宽度不会相应地自动调整其宽度
- python - 如何将字符串 XML 转换为仅具有选定标签及其在 python 中的值的数据框
- java - 为什么 NativeMethodAccessorImpl 声明 InvocationTargetException