首页 > 解决方案 > 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,
        )
    }
)

标签: androidandroid-jetpack-compose

解决方案


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.


推荐阅读