如何将我的自定义视图迁移到 Jetpack Compose?

问题描述 投票:0回答:1

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

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

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

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

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

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

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

android android-jetpack-compose android-custom-view android-jetpack compose-multiplatform
1个回答
3
投票

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

@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")
© www.soinside.com 2019 - 2024. All rights reserved.