Skip to content

互操作性 (Interop)

源:Compose 互操作性 API

Compose 可以与现有的 View 系统完美集成,支持逐步迁移。

1. 在 View 中使用 Compose

如果您想在旧的 XML 布局中嵌入 Compose 组件。

xml
<!-- 添加 ComposeView -->
<androidx.compose.ui.platform.ComposeView
    android:id="@+id/compose_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
kotlin
findViewById<ComposeView>(R.id.compose_view).apply {
    // 设置销毁策略
    setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
    
    setContent {
        MaterialTheme {
            Text("你好,我是来自 Compose 的内容")
        }
    }
}

2. 在 Compose 中使用 View

如果您需要使用尚未有 Compose 版本或过于复杂的 View(如 WebView, MapView)。

使用 AndroidView

AndroidView 接收一个 factory 用于创建 View,以及一个 update 回调用于同步状态。

kotlin
@Composable
fun WebViewScreen(url: String) {
    AndroidView(
        factory = { context ->
            WebView(context).apply {
                webViewClient = WebViewClient()
            }
        },
        update = { webView ->
            webView.loadUrl(url)
        }
    )
}

3. 复用 ViewBinding

如果您已经有了现成的 XML 布局文件,不想重写,但想在 Compose 中显示。

kotlin
// 需要引入依赖: androidx.compose.ui:ui-viewbinding
AndroidViewBinding(MyLayoutBinding::inflate) {
    // 这里的 this 是 MyLayoutBinding 实例
    myTextView.text = "在 Compose 中更新了 XML 的文本"
}

4. 共享设计系统

主题适配器

使用主题适配器,可以让 Compose 直接读取 XML 中的 Material 主题颜色和字体。

kotlin
// build.gradle: com.google.android.material:compose-theme-adapter-3
Mdc3Theme {
    // 这里的 MaterialTheme.colorScheme 会读取 XML 主题
    Button(onClick = {}) { Text("样式一致的按钮") }
}