https://kotlinlang.org logo
#compose
Title
# compose
m

mattinger

02/04/2022, 3:10 PM
So, i’m experimenting with wrapping some of my composables in View classes to bridge the gap between the xml world and the compose world. Yes, programmers could put a raw ComposeView in and set the stuff in code, but it’s more convenient for them this way. I figured i would write a view that extends FrameLayout and adds a compose view, reads xml attribute and renders the contents of the ComposeView based on those. This works all well and good, except that it breaks the xml preview. The preview pane complains that it can’t find the viewTreeLifecycleOwner during the recomposer creation. Code and error screenshot in thread.
Copy code
class TagLabel @JvmOverloads constructor(
    context: Context, attrs:
    AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    init {
        initialize(attrs)
    }

    private fun initialize(attrs: AttributeSet?) {
        val a = context.obtainStyledAttributes(attrs, intArrayOf(android.R.attr.text))
        val text = a.getText(0).toString()
        a.recycle()

        val delegateView = ComposeView(context).apply {
            setContent {
                Text(text = text)
            }
        }

        addView(delegateView)
    }
}
Copy code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="<http://schemas.android.com/apk/res/android>"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="<http://schemas.android.com/apk/res-auto>">

    <TagLabel
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Foobar"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        />


</androidx.constraintlayout.widget.ConstraintLayout>
a

Arjun Achatz

02/04/2022, 4:38 PM
Why not use AbstractComposeView ?
2
m

mattinger

02/04/2022, 7:04 PM
Because I did not realize it was there 😉. I was going by the example in the compose playground.
😂 1
thanks @Arjun Achatz
1
@Arjun Achatz Unfortunately, while AbstractComposeView is much simpler, and exactly what i’m looking for, it still doesn’t render in the XML layout preview. Same error as before.