假设我已经创建了这样的视图的可组合版本:
@Composable fun MyComposable(title: String) {
Text(title)
}
要像常规View一样使用该可组合组件(能够在 XML 中指定其属性),我们应该从AbstractComposeView创建一个自定义视图子类:
// 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)
}
}
这就是我们将如何使用它,就像 XML 中的常规视图一样:
<my.package.name.MyCustomView
android:id="@+id/myView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:myAttribute="Helloooooooooo!" />
和/或在活动中:
val myCustomView = findViewById<MyCustomView>(R.id.myView)
myCustomView.myProperty = "Woohoo!"
感谢 ProAndroidDev 提供这篇文章。
脚注
要为您的视图定义您自己的自定义属性,请参阅这篇文章。
此外,请确保使用AndroidX Core库的-ktx版本,以便能够访问有用的 Kotlin 扩展功能,例如:Context::withStyledAttributes
implementation("androidx.core:core-ktx:1.6.0")