【问题标题】:How to migrate my custom view to Jetpack Compose?如何将我的自定义视图迁移到 Jetpack Compose?
【发布时间】:2021-10-22 17:39:59
【问题描述】:

我有一个 custom view 以传统方式创建:从 View 类继承。

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

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

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

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

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

Android developer documentation 没有提到如何将自定义视图转换为 Compose。

【问题讨论】:

    标签: android android-custom-view android-jetpack-compose android-jetpack composable


    【解决方案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 this article

    脚注

    要为您的视图定义您自己的自定义属性,请参阅this post
    此外,请确保使用 -ktx 版本的 AndroidX Core 库,以便能够访问有用的 Kotlin 扩展函数,例如 Context::withStyledAttributes

    implementation("androidx.core:core-ktx:1.6.0")
    

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多