首页 > 解决方案 > 我可以在 Android 的自定义视图中包装 JetpackCompose 吗?

问题描述

在 Android UI 中,我们可以通过重载来创建自定义视图,View如下所示。

class CustomView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0)
    : View(context, attrs, defStyleAttr) {


    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // Perform the needing drawing
        if (isAttachedToWindow) invalidate()
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val desiredWidth = suggestedMinimumWidth + paddingLeft + paddingRight
        val desiredHeight = suggestedMinimumHeight + paddingTop + paddingBottom

        setMeasuredDimension(View.resolveSize(desiredWidth, widthMeasureSpec),
                View.resolveSize(desiredHeight, heightMeasureSpec))
    }
}

我们可以包装JetpackCompose在 this 中CustomView,以便使用底层的 Drawing 它JetpackCompose吗?

我检查了https://developer.android.com/jetpack/compose/interop/interop-apis,似乎没有说明。

标签: androidandroid-custom-viewandroid-jetpack-compose

解决方案


为了让它工作,我们可以有

class CustomComposeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AbstractComposeView(context, attrs, defStyleAttr) {

    @Composable
    override fun Content() {
        // JetpacCompose code here
    }
}

在 XML 中,我们可以有这样的东西

<com.package.CustomComposeView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="700dp" />

推荐阅读