简体   繁体   中英

How can I make Jetpack Compose AndroidView run a new viewBlock instance on new parameters?

I have a Jetpack Composable function that wraps a WebView instance in an AndroidView:

@Composable
fun createWebView(url: String, viewCache: WebViewCache) {

    AndroidView(viewBlock = { context ->
        viewCache.get(url, context)
    }, update = { wv ->
        Log.d("we are just updating")
    }, modifier = Modifier.fillMaxSize())
}

It works for the first url passed in, but for subsequent different urls, only the update method is called. Is it possible to make the viewBlock lambda be invoked given different parameters? I realize I could call loadUrl on the same WebView instance, but would prefer to cache each url's WebView for my app.

You want to change the state of the Composable, thus you need a mutableState for your URL (mutableStateOf(initUrl)) which is the key to get the cached WebView. I am not familiar with WebView but I would guess you get the new URL inside the update Lambda. Nether the less from wherever you get the new URL you have to update the URL state to tell Compose Runtime to update your UI.

@Composable
fun createWebView(initUrl: String, viewCache: WebViewCache) {
    val context = ContextAmbient.current
    val urlState = remember(initUrl) { mutableStateOf(initUrl) }
    val cacheView = remember(urlState.value, context) {
        viewCache.get(urlState.value, context)
    }
    AndroidView(
        viewBlock = { cacheView },
        update = { wv -> urlState.value = "newvalue" },
        modifier = Modifier.fillMaxSize())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM