【问题标题】:Can I wrap a JetpackCompose in Android's Custom View?我可以在 Android 自定义视图中包装 Jetpack Compose 吗?
【发布时间】:2021-11-16 09:58:43
【问题描述】:

在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 包装在这个CustomView 中,以便底层使用JetpackCompose 来绘制它吗?

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

【问题讨论】:

  • 不确定你在问什么。您发布了自定义视图的代码。您可以使用 AndroidView 将其包含在 Compose 中。
  • 文档清楚地表明您可以通过 ComposeView 小部件在任何地方使用 compose

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


【解决方案1】:

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

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" />

【讨论】:

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