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

R Brian Amesbury

10/29/2019, 2:14 PM
In my single activity app, I am trying to replace the UI that I currently inflate with
Databinding
with
compose
in my fragments. I am doing this:
Copy code
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?
m

Mihai Hrincescu

10/29/2019, 2:32 PM
You need to create a
ViewGroup
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

R Brian Amesbury

10/29/2019, 2:34 PM
That seem like a lot of work to get this to work in fragments, but thanks for the help, i’ll do that
I did this ans it works well, so I wrote a simple extension function to make it easy:
Copy code
fun 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:
Copy code
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
    setComposable {
      Text("Compose With Extension")
    }
Thanks @Mihai Hrincescu for your suggestion!
👍 1
3 Views