Songpol Rungsawang
Songpol Rungsawang

Reputation: 81

Communication between Composable

I have created WebView which is the Android View as Composable. It is the content of the Scaffold of the screen and the Scaffold itself has TopBar as an action bar with a back button on the left, and I want to handle onClicked for the back button to check whether the WebView can go back or not like normal behaviour on the Android View. The question is how to make an onClicked event to know the WebView?

Code:

Scaffold(
    topBar = {
        CustomAppBar(
            title = title,
            onBackPressed = {
                // check webview.canGoBack()
                // if yes, just go back
                // if not, finish activity
            },
        )
    },
    content = {
        CustomWebView(
            url = originalUrl,
        )
    }
)

Upvotes: 1

Views: 1087

Answers (1)

Richard Onslow Roper
Richard Onslow Roper

Reputation: 6835

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.

Upvotes: 1

Related Questions