我可以在 Android 的自定义视图中包装 JetpackCompose 吗?
Can I wrap a JetpackCompose in Android's Custom View?
在AndroidUI中,我们可以通过重载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,好像没有说明。
为了让它工作,我们可以
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" />
在AndroidUI中,我们可以通过重载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,好像没有说明。
为了让它工作,我们可以
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" />