Created
January 28, 2024 08:42
-
-
Save holmeszyx/c32534db1fd4bd01f2ebcdb643c431d0 to your computer and use it in GitHub Desktop.
Compose View
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package xyz.imzyx.nextdemo.ui.comp | |
import android.webkit.WebChromeClient | |
import android.webkit.WebView | |
import android.webkit.WebViewClient | |
import android.widget.FrameLayout | |
import androidx.compose.foundation.layout.Box | |
import androidx.compose.foundation.layout.fillMaxWidth | |
import androidx.compose.runtime.Composable | |
import androidx.compose.runtime.LaunchedEffect | |
import androidx.compose.runtime.MutableState | |
import androidx.compose.runtime.mutableStateOf | |
import androidx.compose.runtime.remember | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.viewinterop.AndroidView | |
/** | |
* | |
* created on 2024/1/28 | |
* @author holmes | |
*/ | |
@Composable | |
fun WebView(modifier: Modifier, url: String) { | |
// https://issuetracker.google.com/issues/242463987?pli=1 | |
val webviewRef: MutableState<WebView?> = remember { | |
mutableStateOf(null) | |
} | |
LaunchedEffect(key1 = url, block = { | |
if (url.isNotEmpty()) { | |
webviewRef.value?.loadUrl(url) | |
} | |
}) | |
Box(modifier = modifier) { | |
AndroidView( | |
modifier = modifier.fillMaxWidth(), | |
factory = { context -> | |
WebView(context).apply { | |
this.layoutParams = FrameLayout.LayoutParams( | |
FrameLayout.LayoutParams.MATCH_PARENT, | |
FrameLayout.LayoutParams.MATCH_PARENT | |
) | |
setBackgroundColor(0) | |
this.clipToOutline = true | |
this.webViewClient = WebViewClient() | |
this.webChromeClient = WebChromeClient() | |
}.also { | |
webviewRef.value = it | |
it.onResume() | |
} | |
}, | |
onRelease = { | |
webviewRef.value?.destroy() | |
webviewRef.value = null | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment