Does anyone know how fragments work in jetpack com...
# compose
j
Does anyone know how fragments work in jetpack compose? the documentation has a bunch of holes in its examples https://developer.android.com/jetpack/compose/interop/interop-apis#compose-in-fragments.
Copy code
class ExampleFragment : Fragment() {

    private var _binding: FragmentExampleBinding? = null
    // This property is only valid between onCreateView and onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentExampleBinding.inflate(inflater, container, false)
        val view = binding.root
        view.composeView.apply {
            // Dispose the Composition when viewLifecycleOwner is destroyed
            setViewCompositionStrategy(
                DisposeOnLifecycleDestroyed(viewLifecycleOwner)
            )
            setContent {
                // In Compose world
                MaterialTheme {
                    Text("Hello Compose!")
                }
            }
        }
        return view
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
Like where does FragmentExampleBinding? How does the xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="<http://schemas.android.com/apk/res/android>"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/hello_world"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello Android!" />

    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
get into the above code? I see no reference to any of the id's yet
Some how it picks up the "Hello Android!" with out referencing it?
i
Which transforms
fragment_example.xml
into
FragmentExampleBinding
- an object that has a field for each view with an id - that's why there's a
view.composeView
field
j
ohhh ok now that all makes sense now
i
So
view.composeView
is really just a super smart, cached version of
view.findViewById<ComposeView>(R.id.compose_view)
that is generated for you
I think that example is slightly off though - the
composeView
field is on
binding
, not on
binding.root
(that's just a normal View, not the smart binding object)