Jeeva
Jeeva

Reputation: 4845

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?

Upvotes: 1

Views: 3896

Answers (1)

Yshh
Yshh

Reputation: 832

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()
        }
    }
}

Upvotes: 3

Related Questions