R Brian Amesbury
10/29/2019, 2:14 PMDatabinding with compose in my fragments. I am doing this:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
container.apply {
this?.let {
it.setContent {
Text("Compose")
}
}
}
It is failing with this exception: java.lang.IllegalStateException: Views added to a FragmentContainerView must be associated with a Fragment. View androidx.ui.core.AndroidComposeView{99eebb1 VFED..... ......I. 0,0-0,0} is not associated with a Fragment.
The container that is passed in to onCreateView is a FragmentContainerView which I am guessing is the view that is inflated in the activity to host the NavGraph. How can compose my UI in my fragment, and set it as the content?Mihai Hrincescu
10/29/2019, 2:32 PMViewGroup pass your `composable`using the extension function setContent(), this will add your composable as a child of the ViewGroup then return the ViewGroup as normal this way the fragment can add and remove the view from the hierarchy as it needs to. Also you need to set the LayoutParams of your ViewGroup.R Brian Amesbury
10/29/2019, 2:34 PMR Brian Amesbury
10/29/2019, 3:37 PMfun androidx.fragment.app.Fragment.setComposable(content: @Composable() () -> Unit): View? =
context?.let {
FrameLayout(it).apply {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
setContent(content)
}
}
It is consumed like this:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
setComposable {
Text("Compose With Extension")
}
Thanks @Mihai Hrincescu for your suggestion!