Is it impossible to preview a custom view that emb...
# compose
l
Is it impossible to preview a custom view that embeds a
ComposeView
from Android Studio? It complains about missing
ViewTreeLifecycleOwner
, and
ViewTressSavedStateRegistryOwner
😕 Also, does it mean it's impossible to have a compose view outisde of an Activity? I'm thinking about the few
WindowManager
use cases.
a
File the former issue and no, you can create, configure, and drive both of those dependencies outside of an activity
l
Are you sure about that? From the interop APIs doc that I just checked out:
You must attach the 
ComposeView
 to a 
ViewTreeLifecycleOwner
.
Getting a standalone
ViewTreeLifecycleOwner
instance for use in the
WindowManager
is not really possible, so I'm wondering how it's supposed to work 🤔
a
Why do you think it's not possible?
LifecycleOwner
is just an interface and
LifecycleRegistry
is public
l
There's also the non documented
ViewTressSavedStateRegistryOwner
that you can't fake
When you use
WindowManager
, you don't have a
Lifecycle
. Making a custom one doesn't seem so great to me.
z
Making a custom lifecycle for this case is kind of like making a custom coroutine scope imo - ideally something the infrastructure does for you, but sometimes that infrastructure isn’t there (yet)
a
right, and directly managing windows outside the scope of an activity is niche enough that paving this dirt road isn't likely to be a priority for a while.
l
That "dirty road" which for now is only previewing via a View in the IDE, could be making an accessibility service, be it to customize the device, bring special features, or provide accessibility features. In any cases, I think it can be more… accessible 🙂 So I wrote all of this boilerplate:
Copy code
val lifecycleOwner = object : LifecycleOwner {
            private val lifecycle = LifecycleRegistry(this)
            init {
                lifecycle.currentState = Lifecycle.State.STARTED
            }
            override fun getLifecycle(): Lifecycle = lifecycle
        }
        val savedStateRegistryOwner = object : SavedStateRegistryOwner {

            private val controller = SavedStateRegistryController.create(this)
            override fun getLifecycle() = lifecycleOwner.lifecycle
            override fun getSavedStateRegistry(): SavedStateRegistry = controller.savedStateRegistry
        }

ViewTreeLifecycleOwner.set(it.root, lifecycleOwner)
            ViewTreeSavedStateRegistryOwner.set(it.root, savedStateRegistryOwner)
But I still get an error:
Copy code
java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from com.android.layoutlib.bridge.impl.Layout{3feb6b45 V.E...... ......ID 0,0-0,0}   at androidx.compose.ui.platform.WindowRecomposer_androidKt.createLifecycleAwareViewTreeRecomposer(…)
…