Composes an Android [View] obtained from [factory].
AndroidViewSample
@Suppress("SetTextI18n")
@Composable
fun AndroidViewSample() {
// Compose a TextView.
AndroidView({ context -> TextView(context).apply { text = "This is a TextView" } })
// Compose a View and update its size based on state. Note the modifiers.
var size by remember { mutableStateOf(20) }
AndroidView(::View, Modifier.clickable { size += 20 }.background(Color.Blue)) { view ->
view.layoutParams = ViewGroup.LayoutParams(size, size)
}
}
AndroidViewWithReleaseSample
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
@Composable
fun AndroidViewWithReleaseSample() {
// Compose a View that needs to be cleaned up when removed from the UI
class LifecycleAwareView(context: Context) : View(context) {
var lifecycle: Lifecycle? = null
set(value) {
field?.removeObserver(observer)
value?.addObserver(observer)
field = value
}
private val observer = LifecycleEventObserver { source, event ->
// React to the event
}
}
val lifecycle = LocalLifecycleOwner.current.lifecycle
AndroidView(
factory = { context -> LifecycleAwareView(context) },
update = { view -> view.lifecycle = lifecycle },
onRelease = { view ->
// Need to release the lifecycle to prevent a memory leak
view.lifecycle = null
},
)
}
ReusableAndroidViewInLazyColumnSample
@Composable
fun ReusableAndroidViewInLazyColumnSample() {
val urls =
listOf(
"https://developer.android.com/jetpack/compose",
"https://google.github.io/accompanist/",
"https://android-developers.googleblog.com/",
"https://io.google/",
// ...
)
LazyVerticalGrid(columns = GridCells.Adaptive(512.dp)) {
items(urls) { url ->
AndroidView(
factory = { context ->
WebView(context).apply {
settings.javaScriptEnabled = true
webViewClient =
object : WebViewClient() {
// Optional overrides for WebViewClient
}
}
},
modifier = Modifier.fillMaxWidth().aspectRatio(1f),
update = { webView -> webView.loadUrl(url) },
onReset = { webView ->
webView.stopLoading()
webView.loadUrl("about:blank")
webView.clearHistory()
},
)
}
}
}
@Composable
fun ViewInComposeNestedScrollInteropSample() {
Box(
Modifier.fillMaxSize()
.scrollable(
rememberScrollableState {
// view world deltas should be reflected in compose world
// components that participate in nested scrolling
it
},
Orientation.Vertical,
)
) {
AndroidView({ context ->
LayoutInflater.from(context).inflate(android.R.layout.activity_list_item, null).apply {
// Nested Scroll Interop will be Enabled when
// nested scroll is enabled for the root view
ViewCompat.setNestedScrollingEnabled(this, true)
}
})
}
}