简体   繁体   中英

Dynamically show AndroidView in Jetpack Compose

I am building an application that has list of webviews, and I want show a webview depending on a condition. As webview not supported by Jetpack Compose, I used the AndroidView to use the native WebView.

for (tab in vm.tabs) {
    if (tab.tabId == vm.currentTab.tabId) {
        AndroidView(
            factory = {
                WebView(it).apply {
                    settings.javaScriptEnabled = true
                    webChromeClient = WebChromeClient()
                    webViewClient = WebViewClient()
                    loadUrl(tab.url)
                }
            },
            modifier = Modifier.fillMaxSize()
        )
    }
}

I googled and found out that AndroidView will only initialized once and the update will be called on recomposition. I don't want to update a single webview. I only want to show a whole new webview for each matched condition.

How can I achieve this?

You can use Google's Accompanist , A library which provides a Jetpack Compose wrapper around Android's WebView.

simple example

for (tab in vm.tabs) {
    if (tab.tabId == vm.currentTab.tabId) {
        val state = rememberWebViewState(tab.url)
        WebView(
            state,
            Modifier,
            onCreated = {
                it.settings.javaScriptEnabled = true
                //...
            }
        )
        if (state.isLoading) {
            CircularProgressIndicator()
        }
    }
}

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