1

我有一个以传统方式创建的自定义视图:从View类继承。

具体来说,我的自定义视图有许多可以在 XML 布局中分配的自定义属性(及其相应的 Kotlin 属性):

<com.example.MyCustomView
    app:myCustomAttr1 = "..."
    app:myCustomAttr2 = "..."/>

如何提供我的可组合的视图版本,以便用户可以在 XML 中使用它?

除了使用AndroidView类在 Jetpack Compose 中加载传统的 Android 视图之外,如何我的视图转换为“真正的”Compose 组件?

我应该为自定义视图的每个部分提供单独的可组合项吗?例如,一个可组合的饼图,另一个可组合的图例框?

Android 开发者文档没有提到如何将自定义视图转换为 Compose。

4

1 回答 1

1

假设我已经创建了这样的视图的可组合版本:

@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")
于 2021-09-19T19:30:21.900 回答