Jason Inbody
08/21/2021, 3:55 AMJason Inbody
08/21/2021, 3:57 AMclass 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
<?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 yetJason Inbody
08/21/2021, 3:57 AMJason Inbody
08/21/2021, 3:58 AMIan Lake
08/21/2021, 4:05 AMIan Lake
08/21/2021, 4:06 AMfragment_example.xml
into FragmentExampleBinding
- an object that has a field for each view with an id - that's why there's a view.composeView
fieldJason Inbody
08/21/2021, 4:07 AMIan Lake
08/21/2021, 4:07 AMview.composeView
is really just a super smart, cached version of view.findViewById<ComposeView>(R.id.compose_view)
that is generated for youIan Lake
08/21/2021, 4:08 AMcomposeView
field is on binding
, not on binding.root
(that's just a normal View, not the smart binding object)