【发布时间】:2021-04-15 08:03:38
【问题描述】:
如何在同一个活动中添加 Jetpack Compose 和 xml?举个例子就完美了。
【问题讨论】:
-
请在此处附上您的问题代码!
标签: android kotlin android-custom-view android-jetpack-compose android-jetpack
如何在同一个活动中添加 Jetpack Compose 和 xml?举个例子就完美了。
【问题讨论】:
标签: android kotlin android-custom-view android-jetpack-compose android-jetpack
如果你想在你的 XML 文件中使用 Compose,你可以将它添加到你的布局文件中:
<androidx.compose.ui.platform.ComposeView
android:id="@+id/my_composable"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
然后,设置内容:
findViewById<ComposeView>(R.id.my_composable).setContent {
MaterialTheme {
Surface {
Text(text = "Hello!")
}
}
}
如果你想要相反的,即在你的撰写中使用 XML 文件,你可以使用这个:
AndroidView(
viewBlock = { context: Context ->
val view = LayoutInflater.from(context)
.inflate(R.layout.my_layout, null, false)
val textView = view.findViewById<TextView>(R.id.text)
// do whatever you want...
view // return the view
},
update = { view ->
// Update the view
}
)
【讨论】:
https://developer.android.com/jetpack/compose/interop?hl=en
要嵌入 XML 布局,请使用
androidx.compose.ui:ui-viewbinding库提供的 AndroidViewBinding API。为此,您的项目必须启用视图绑定。 AndroidView 与许多其他内置可组合项一样,采用可用于例如设置其在父可组合项中的位置的 Modifier 参数。
@Composable
fun AndroidViewBindingExample() {
AndroidViewBinding(ExampleLayoutBinding::inflate) {
exampleView.setBackgroundColor(Color.GRAY)
}
}
【讨论】:
如果你想像普通的View一样提供你的组合(能够在XML中指定它的属性),从AbstractComposeView子类化。
@Composable fun MyComposable(title: String) {
Text(title)
}
// Do not forget these two imports for the delegation (by) to work
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
class MyCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : AbstractComposeView(context, attrs, defStyle) {
var myProperty by mutableStateOf("A string")
init {
// See the footnote
context.withStyledAttributes(attrs, R.styleable.MyStyleable) {
myProperty = getString(R.styleable.MyStyleable_myAttribute)
}
}
// The important part
@Composable override fun Content() {
MyComposable(title = myProperty)
}
}
这就是您可以像使用普通视图一样使用它的方式:
<my.package.name.MyCustomView
android:id="@+id/myView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:myAttribute="Helloooooooooo!" />
感谢 ProAndroidDev this article。
要为您的视图定义您自己的自定义属性,请参阅this post。
此外,请确保使用 -ktx 版本的 AndroidX Core 库,以便能够访问有用的 Kotlin 扩展函数,例如 Context::withStyledAttributes:
implementation("androidx.core:core-ktx:1.6.0")
【讨论】: