XML layouts and ViewBinding

How XML layouts become View objects, how ViewBinding replaces findViewById safely, and how to avoid the Fragment binding leak. About 20 minutes.

Why it matters

  • New screens are Compose, but many production apps still ship a lot of XML screens. You will read and fix them in your first week.
  • Interviewers still ask about findViewById, ViewBinding and ConstraintLayout, especially for apps older than a few years.
  • Two classic bugs live here: a leaked Fragment view and a null view in a layout variant. Both reach production often.
  • Migrating a screen to Compose starts with understanding what the XML did.

The simple explanation

Think of a flat-pack wardrobe. The XML file is the instruction sheet and the parts list. At runtime a tool called the LayoutInflater reads the sheet and builds real View objects, one per tag.

Now you need to reach one of the parts, say the handle:

  • findViewById is like shouting the part number into the room. You get a part back, but the compiler cannot check that the id exists or that it is a handle.
  • ViewBinding is like getting a printed label for every part at build time. Wrong names do not compile.
  • DataBinding adds expressions inside the XML itself, like wiring a light to a switch on the sheet.

The real names:

ToolWhat it doesStatus
findViewByIdLooks up a view by id at runtime. Unchecked type, may return null.Works, but avoid in new code
Kotlin synthetics (kotlinx.android.synthetic)Used the id as a property nameDeprecated in Kotlin 1.4.20 and removed in Kotlin 1.8. Migrate to ViewBinding
ViewBindingGenerates a binding class per layout, with typed fieldsCurrent default for XML
DataBindingViewBinding plus @{} expressions and observable data, wrapped in <layout>Still works, heavier, needs an annotation processor

How a layout reaches the screen: inflate (XML to Views), then three passes: measure (how big), layout (where), draw (paint). A size change (requestLayout) runs all three again. A visual-only change (invalidate) runs only draw. Deep nesting makes the measure pass slow, because parents measure children, and some parents measure them twice.

  • ConstraintLayout positions views against each other and the parent. One flat level replaces many nested LinearLayouts.
  • 0dp with constraints means "match constraints": fill the space the constraints allow.
  • LinearLayout is fine for simple rows. Use layout_weight sparingly in deep trees, because weighted children can be measured more than once.

Notes

  • Turn ViewBinding on per module: buildFeatures { viewBinding = true } in the module's Gradle file.
  • The class name comes from the file name: fragment_profile.xml becomes FragmentProfileBinding. Ids become camelCase fields: user_name becomes userName.
  • In an Activity: ActivityMainBinding.inflate(layoutInflater), then setContentView(binding.root).
  • In a Fragment, the view is destroyed before the Fragment is. A binding held in a field after onDestroyView leaks the whole view tree.
  • Pattern: a nullable _binding set in onViewCreated, a binding getter for use, and _binding = null in onDestroyView.
  • If a view exists in only some layout variants (for example layout-land), its binding field is nullable. findViewById would silently return null and crash later.
  • An <include> that has an android:id gets a field holding the included layout's own binding.
  • ViewBinding does no data binding and no logic. It only gives safe access. Use a ViewModel for state.
  • tools: attributes (like tools:text) are for the preview only and are removed at build time.
  • Check hierarchy depth with Layout Inspector before blaming the list or the animation.

Code example

A Fragment that uses ViewBinding correctly, collects state with the view lifecycle, and clears the binding. The layout is a flat ConstraintLayout.

<!-- res/layout/fragment_profile.xml (flat, one level) -->
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">
 
    <TextView android:id="@+id/title" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
 
    <Button android:id="@+id/save_button" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Save"
        app:layout_constraintTop_toBottomOf="@id/title"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class ProfileFragment : Fragment(R.layout.fragment_profile) {
 
    private var _binding: FragmentProfileBinding? = null
    private val binding get() = _binding!!       // valid only between onViewCreated and onDestroyView
    private val viewModel: ProfileViewModel by viewModels()
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentProfileBinding.bind(view)   // layout already inflated by the constructor
        binding.saveButton.setOnClickListener { viewModel.save() }
 
        // Use the VIEW lifecycle, not the Fragment lifecycle, for UI work.
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.name.collect { binding.title.text = it }
            }
        }
    }
 
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null                            // lets the view tree be garbage collected
    }
}

ProfileViewModel here is assumed to expose a name Flow of String and a save() function.

In production

The profile screen that ate memory
  • Users who moved back and forth between screens saw the app slow down, then crash with OutOfMemoryError on low-end phones.
  • Cause: a Fragment on the back stack keeps its instance alive but destroys its view. The Fragment held binding in a field, so the old view tree, with images, stayed in memory for every screen on the stack.
The fix
  1. Reproduce it. Add LeakCanary to the debug build, open the screen, go forward, come back. It reports the leaked view and the field that holds it.
  2. Set _binding = null in onDestroyView.
  3. Also clear things the binding owns that outlive the view, for example binding.list.adapter = null when the adapter is a Fragment field.
  4. Keep LeakCanary in debug builds so it cannot return silently.
The rotation crash from a missing view
  • A small share of users crashed with a NullPointerException right after rotating to landscape.
  • Cause: layout-land/activity_order.xml was edited by another developer and the promo_banner view was removed. The code used findViewById(R.id.promo_banner) and called a method on the null result.
The fix
  1. Reproduce: run the screen on a device or emulator, rotate, read the stack trace.
  2. Migrate the screen to ViewBinding. The field for a view that is missing in one variant becomes nullable, so Kotlin forces ?. and the crash cannot compile.
  3. Add the rotation case to the manual test checklist for any screen with layout variants.

Common mistakes

  • Keeping the binding after onDestroyView. The Fragment outlives its view, so the view tree leaks. Null it out.
  • Using the Fragment itself (this or lifecycleScope) instead of viewLifecycleOwner. The collector keeps running after the view is gone and touches a dead binding. Use viewLifecycleOwner.
  • Nesting many LinearLayouts with weights. Measure cost grows with depth. Flatten with ConstraintLayout.
  • Keeping Kotlin synthetics in old code. The kotlin-android-extensions plugin was removed in Kotlin 1.8, so they block Kotlin upgrades. Use ViewBinding.
  • Putting logic in DataBinding expressions. It cannot be unit tested and is hard to debug. Keep expressions trivial or skip DataBinding.
  • Calling findViewById on a view from another layout. It returns null and fails at runtime. Use the binding of that layout.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between findViewById, ViewBinding and DataBinding?”

“Why do you set the binding to null in onDestroyView?”

“Why is ConstraintLayout recommended over nested LinearLayouts?”

Quiz

A Fragment holds its binding in a field and never clears it. What happens when the Fragment goes to the back stack?

What does ViewBinding generate for activity_main.xml?

A view id exists in layout/ but not in layout-land/. What type does the ViewBinding field have?

Which statement about Kotlin synthetics is correct?

0 of 4 answered

Mini task

Take any screen from a sample project (or build one with a TextView and a Button in a Fragment):

  1. Enable viewBinding in the module and replace every findViewById with the binding.
  2. Use the _binding pattern and clear it in onDestroyView.
  3. Add LeakCanary in debug, open the screen, navigate to another screen and back three times.
  4. Create a layout-land variant that removes the Button and rotate the device.

You are done when LeakCanary reports no leak, and you can explain why the button field is nullable after step 4.

Next: RecyclerView essentials