View Binding vs findViewById and Data Binding

Views, layouts and RecyclerView Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

A Fragment keeps private lateinit var binding and LeakCanary reports the old view tree after navigating back. Fix?

Options
Hint 1 of 1

When does a Fragment's view die?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Use a nullable _binding set in onCreateView and cleared in onDestroyView

Correct. The Fragment instance outlives its view on the back stack.

Why not the others?
  • B Switch to Data Binding. Same leak if the binding is kept.
  • C Call binding.unbind() in onDestroy. onDestroy is too late; the view was destroyed earlier.
  • D Make the binding a companion object. That's a global leak.

30-second answer

View Binding generates a class per layout with a typed, non-null field for each view with an ID, so there's no casting and no wrong-ID crashes. It has no runtime cost beyond inflation. Data Binding adds expressions in XML and observation, at the price of build time and logic in layouts. For View-based screens, View Binding is the usual choice; new UI is mostly Compose.

Practise saying it · 30 s. No recording, just a timer

Compare View Binding and Data Binding.

Say your answer out loud, then check which of these points you covered:

  • Typed, null-safe view references
  • No runtime cost
  • Data Binding adds XML expressions
  • Clear in onDestroyView

Deep dive

In Fragments, clear the binding in onDestroyView.

Views that exist only in some configurations become nullable fields.

Kotlin synthetics were removed; View Binding is the replacement.

Data Binding can observe StateFlow if you set a lifecycle owner.

Common mistakes

  • Keeping the Fragment binding after onDestroyView.
  • Putting business logic in Data Binding expressions.
  • Still using kotlin-android-extensions.

Senior take & follow-ups

Short and practical: name the leak rule for Fragments.

Follow-up questions

Think of your answer first, then open the hint.

  1. What replaced Kotlin synthetics?

    Show hint

    View Binding.

  2. Why clear the binding in onDestroyView?

    Show hint

    The Fragment can outlive its view on the back stack.

Suggest a fix if something here is wrong or out of date.