Views you will still meet cheat sheet
Key ideas
- ViewBinding generates a class from the XML file name (
fragment_profile.xml→FragmentProfileBinding); ids become camelCase fields. - In a Fragment the view is destroyed before the Fragment, so null the binding in
onDestroyViewor the whole view tree leaks. ListAdapterwrapsAsyncListDiffer; callsubmitListwith a new list instance—mutating the old one is ignored.areItemsTheSamemust compare the item id only; comparing whole objects turns every edit into a remove-plus-insert pair.- A recycled
ViewHolderkeeps the previous item's visual state; assign every mutable property inonBindViewHolder. ComposeViewin a Fragment should useDisposeOnViewTreeLifecycleDestroyedset beforesetContent.AndroidViewfactorycreates the View once;updatehandles changing state;onReleaseremoves listeners and detaches adapters.tools:attributes (e.g.tools:text) are preview-only and stripped at build time.kotlin-android-extensionswas removed in Kotlin 1.8; use ViewBinding instead of synthetics.findViewByIdon a view that belongs to another layout returns null and crashes at runtime; use that layout's binding.
APIs at a glance
| API or term | Use it for |
|---|---|
buildFeatures { viewBinding = true } | Enable ViewBinding generation in the module's Gradle file. |
FragmentProfileBinding | Generated class from fragment_profile.xml; gives typed access to every id. |
ListAdapter | Adapter that wraps AsyncListDiffer and DiffUtil for animated list updates. |
DiffUtil.ItemCallback | Define areItemsTheSame and areContentsTheSame so DiffUtil can compute minimal changes. |
submitList | Hand a new list to ListAdapter; triggers a background diff and animated update. |
getChangePayload | Return a payload token so onBindViewHolder can do a partial bind instead of a full one. |
ComposeView | Host a Compose tree inside a View-based layout or Fragment. |
ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed | Dispose composition when the Fragment's view is destroyed; safe for Fragment-scoped ComposeView. |
AndroidView | Embed a legacy View (or XML layout) inside a Compose layout. |
AndroidViewBinding | Inflate an existing XML layout through its ViewBinding class inside Compose. |
AndroidFragment | Embed a whole Fragment inside a Compose layout (from fragment-compose). |
onRelease | Clean up listeners, players, and adapters when an AndroidView leaves composition. |
Snippets
Fragment ViewBinding lifecycle
private var _binding: FragmentProfileBinding? = null
private val binding get() = _binding!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
_binding = FragmentProfileBinding.bind(view)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}ListAdapter with DiffUtil and payloads
data class Item(val id: Long, val title: String, val isRead: Boolean)
const val PAYLOAD_READ = "read"
object ItemDiff : DiffUtil.ItemCallback<Item>() {
override fun areItemsTheSame(old: Item, new: Item) = old.id == new.id
override fun areContentsTheSame(old: Item, new: Item) = old == new
override fun getChangePayload(old: Item, new: Item): Any? =
if (old.copy(isRead = new.isRead) == new) PAYLOAD_READ else null
}
class ItemAdapter : ListAdapter<Item, ItemAdapter.VH>(ItemDiff) {
class VH(val text: TextView) : RecyclerView.ViewHolder(text)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = VH(TextView(parent.context))
override fun onBindViewHolder(holder: VH, position: Int) {
val item = getItem(position)
holder.text.text = item.title
holder.text.alpha = if (item.isRead) 0.5f else 1f
}
override fun onBindViewHolder(holder: VH, position: Int, payloads: MutableList<Any>) {
if (PAYLOAD_READ in payloads) holder.text.alpha = if (getItem(position).isRead) 0.5f else 1f
else onBindViewHolder(holder, position)
}
}ComposeView in a Fragment
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?,
): View = ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent { MaterialTheme { Text("Hello from Compose") } }
}AndroidView embedding a RecyclerView
@Composable
fun LegacyList(adapter: RecyclerView.Adapter<*>, modifier: Modifier = Modifier) {
AndroidView(
factory = { ctx ->
RecyclerView(ctx).apply {
layoutManager = LinearLayoutManager(ctx)
this.adapter = adapter
}
},
modifier = modifier,
update = { rv -> /* set values that change with state */ },
onRelease = { rv -> rv.adapter = null },
)
}Rules of thumb
- Prefer
submitListwith a freshly created list over mutating the list you already submitted. - Never keep a ViewBinding reference past
onDestroyView; null it out to avoid leaking the view tree. - Prefer
viewLifecycleOwner.lifecycleScopeover the Fragment's ownlifecycleScopewhen collecting flows that touch views. - Never compare whole objects in
areItemsTheSame; use the stable id so edits do not become remove-plus-insert. - Prefer
ConstraintLayoutover nestedLinearLayoutwith weights to keep measure cost flat. - Never call
notifyDataSetChanged()on aListAdapter; letsubmitListdispatch the diff.
Gotchas
- Keeping the binding after onDestroyView. The Fragment outlives its view, so the binding holds the entire view tree in memory. Null
_bindinginonDestroyView. - Using the Fragment's lifecycleScope instead of viewLifecycleOwner.lifecycleScope. The collector keeps running after the view is gone and touches a dead binding, causing crashes. Collect with
viewLifecycleOwner.lifecycleScopeandrepeatOnLifecycle(STARTED). - Comparing whole objects in areItemsTheSame. Every edit looks like a remove plus insert, causing flicker and extra binding. Compare only the item id.
- Mutating the submitted list and calling submitList again.
submitListignores the same list instance, so the UI never updates. Submit a new list, e.g.list.toMutableList().apply { add(item) }. - Heavy or non-idempotent work in AndroidView update.
updatere-runs on every state change; callingnotifyDataSetChanged()or reassigning the adapter causes jank. Keep it cheap and usesubmitListinstead. - Not cleaning up in onRelease. Listeners on long-lived objects and an adapter held by a Fragment keep the old
Viewalive after it leaves composition. Remove them inonRelease.
Quick interview answers
Why must you null the ViewBinding reference in onDestroyView?
In a Fragment the view is destroyed before the Fragment itself, so a binding held in a field keeps the entire view tree alive after it is gone. Setting _binding = null in onDestroyView releases the tree and prevents a memory leak.
What is the difference between areItemsTheSame and areContentsTheSame in DiffUtil.ItemCallback?
areItemsTheSame checks identity (usually the id) and decides whether two positions refer to the same logical item. areContentsTheSame is only called for pairs that passed the identity check and decides whether the visible data changed, so a data-class == is usually sufficient.
Why use DisposeOnViewTreeLifecycleDestroyed for a ComposeView inside a Fragment?
The default strategy disposes on detach from window, which does not match the Fragment's view lifecycle. DisposeOnViewTreeLifecycleDestroyed disposes exactly when onDestroyView fires, so composition state survives a temporary detach but is released when the view is truly gone.
What happens if you call submitList with the same list instance you submitted before?
ListAdapter detects the identical reference and does nothing, so the UI never updates. Always create a new list, for example list.toMutableList().apply { add(item) }, before calling submitList.
What is the recycled-state bug in RecyclerView and how do you fix it?
A reused ViewHolder still shows the previous item's visual state such as a checked CheckBox, visibility, or a running image load. Assign a definite value to every mutable property in onBindViewHolder so nothing leaks from the old item.
What is the difference between factory and update in AndroidView?
factory runs once when the node enters composition and is the place to create or inflate the View and set values that never change. update runs after factory and again whenever the state it reads changes, so put changing values there and keep the block cheap and safe to call repeatedly.