Views you will still meet cheat sheet

Revise ViewBinding, RecyclerView with ListAdapter and DiffUtil, and Compose-to-Views interop for Android interview prep.

Key ideas

  1. ViewBinding generates a class from the XML file name (fragment_profile.xml → FragmentProfileBinding); ids become camelCase fields.
  2. In a Fragment the view is destroyed before the Fragment, so null the binding in onDestroyView or the whole view tree leaks.
  3. ListAdapter wraps AsyncListDiffer; call submitList with a new list instance—mutating the old one is ignored.
  4. areItemsTheSame must compare the item id only; comparing whole objects turns every edit into a remove-plus-insert pair.
  5. A recycled ViewHolder keeps the previous item's visual state; assign every mutable property in onBindViewHolder.
  6. ComposeView in a Fragment should use DisposeOnViewTreeLifecycleDestroyed set before setContent.
  7. AndroidView factory creates the View once; update handles changing state; onRelease removes listeners and detaches adapters.
  8. tools: attributes (e.g. tools:text) are preview-only and stripped at build time.
  9. kotlin-android-extensions was removed in Kotlin 1.8; use ViewBinding instead of synthetics.
  10. findViewById on a view that belongs to another layout returns null and crashes at runtime; use that layout's binding.

APIs at a glance

API or termUse it for
buildFeatures { viewBinding = true }Enable ViewBinding generation in the module's Gradle file.
FragmentProfileBindingGenerated class from fragment_profile.xml; gives typed access to every id.
ListAdapterAdapter that wraps AsyncListDiffer and DiffUtil for animated list updates.
DiffUtil.ItemCallbackDefine areItemsTheSame and areContentsTheSame so DiffUtil can compute minimal changes.
submitListHand a new list to ListAdapter; triggers a background diff and animated update.
getChangePayloadReturn a payload token so onBindViewHolder can do a partial bind instead of a full one.
ComposeViewHost a Compose tree inside a View-based layout or Fragment.
ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyedDispose composition when the Fragment's view is destroyed; safe for Fragment-scoped ComposeView.
AndroidViewEmbed a legacy View (or XML layout) inside a Compose layout.
AndroidViewBindingInflate an existing XML layout through its ViewBinding class inside Compose.
AndroidFragmentEmbed a whole Fragment inside a Compose layout (from fragment-compose).
onReleaseClean 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 submitList with 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.lifecycleScope over the Fragment's own lifecycleScope when collecting flows that touch views.
  • Never compare whole objects in areItemsTheSame; use the stable id so edits do not become remove-plus-insert.
  • Prefer ConstraintLayout over nested LinearLayout with weights to keep measure cost flat.
  • Never call notifyDataSetChanged() on a ListAdapter; let submitList dispatch the diff.

Gotchas

  • Keeping the binding after onDestroyView. The Fragment outlives its view, so the binding holds the entire view tree in memory. Null _binding in onDestroyView.
  • 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.lifecycleScope and repeatOnLifecycle(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. submitList ignores 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. update re-runs on every state change; calling notifyDataSetChanged() or reassigning the adapter causes jank. Keep it cheap and use submitList instead.
  • Not cleaning up in onRelease. Listeners on long-lived objects and an adapter held by a Fragment keep the old View alive after it leaves composition. Remove them in onRelease.

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.

Go deeper