XML layouts and ViewBinding
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:
findViewByIdis 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:
| Tool | What it does | Status |
|---|---|---|
findViewById | Looks 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 name | Deprecated in Kotlin 1.4.20 and removed in Kotlin 1.8. Migrate to ViewBinding |
| ViewBinding | Generates a binding class per layout, with typed fields | Current default for XML |
| DataBinding | ViewBinding 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. 0dpwith constraints means "match constraints": fill the space the constraints allow.LinearLayoutis fine for simple rows. Uselayout_weightsparingly 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.xmlbecomesFragmentProfileBinding. Ids become camelCase fields:user_namebecomesuserName. - In an Activity:
ActivityMainBinding.inflate(layoutInflater), thensetContentView(binding.root). - In a Fragment, the view is destroyed before the Fragment is. A binding held in a field after
onDestroyViewleaks the whole view tree. - Pattern: a nullable
_bindingset inonViewCreated, abindinggetter for use, and_binding = nullinonDestroyView. - If a view exists in only some layout variants (for example
layout-land), its binding field is nullable.findViewByIdwould silently return null and crash later. - An
<include>that has anandroid:idgets 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 (liketools: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
- Users who moved back and forth between screens saw the app slow down, then crash with
OutOfMemoryErroron low-end phones. - Cause: a Fragment on the back stack keeps its instance alive but destroys its view. The Fragment held
bindingin a field, so the old view tree, with images, stayed in memory for every screen on the stack.
- 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.
- Set
_binding = nullinonDestroyView. - Also clear things the binding owns that outlive the view, for example
binding.list.adapter = nullwhen the adapter is a Fragment field. - Keep LeakCanary in debug builds so it cannot return silently.
- A small share of users crashed with a
NullPointerExceptionright after rotating to landscape. - Cause:
layout-land/activity_order.xmlwas edited by another developer and thepromo_bannerview was removed. The code usedfindViewById(R.id.promo_banner)and called a method on the null result.
- Reproduce: run the screen on a device or emulator, rotate, read the stack trace.
- 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. - 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 (
thisorlifecycleScope) instead ofviewLifecycleOwner. The collector keeps running after the view is gone and touches a dead binding. UseviewLifecycleOwner. - Nesting many
LinearLayouts with weights. Measure cost grows with depth. Flatten with ConstraintLayout. - Keeping Kotlin synthetics in old code. The
kotlin-android-extensionsplugin 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
findViewByIdon 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):
- Enable
viewBindingin the module and replace everyfindViewByIdwith the binding. - Use the
_bindingpattern and clear it inonDestroyView. - Add LeakCanary in debug, open the screen, navigate to another screen and back three times.
- Create a
layout-landvariant 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.