What does Android view binding generate from an XML layout, and what does it fix compared with findViewById?
answer
- one class per layout file
- only views that have an id
- null safety and type safety
- a fragment outlives its view
basics
~20 sView binding generates one class per layout, such as ResultProfileBinding, with a typed field for every view that has an id plus a root reference. Wrong ids or types fail at compile time instead of crashing at runtime.
solid answer
~40 sWith `buildFeatures { viewBinding = true }` in a module, the build generates a binding class for every layout: `result_profile.xml` becomes `ResultProfileBinding`, with a field for each view that has an `android:id` (`@+id/user_bio` becomes `userBio`) and `root` for the root view. You call `ResultProfileBinding.inflate(layoutInflater)` and pass `binding.root` to `setContentView()`. Compared with `findViewById`, the fields are typed, so there is no cast to get wrong, and they cannot point at an id missing from the layout; a view present only in some configurations becomes a nullable field. In a fragment, inflate in `onCreateView()` and clear the reference in `onDestroyView()`, because the fragment outlives its view.
code
kotlin · 25 linesclass ArticleFragment : Fragment() {
private var _binding: FragmentArticleBinding? = null
// Valid only between onCreateView and onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentArticleBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.headline.text = getString(R.string.loading)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}go deeper
Recall how to enable view binding, how the class and field names are derived, and the inflate-then-setContentView pattern in an activity.
Explain the null and type safety over findViewById, the nullable field for configuration-only views, and why fragments clear the binding in onDestroyView.
Catch the fragment binding leak in review, use tools:viewBindingType for views that differ by configuration, and choose between view binding and data binding per layout.
Set the module default: view binding on, findViewById out of new code, data binding only where expressions earn their build cost.
## Resource ids underneath Every view a layout wants to reach from code needs an **id**. Writing `android:id="@+id/headline"` asks the resource compiler to create the id if it does not exist yet (the `+`), and the build generates an integer constant for it, `R.id.headline`, in the module's `R` class. At runtime the id is also known by its package-qualified name, such as `com.example.news:id/headline`, which is what layout inspection and UI testing tools show; locating views that way in a test is covered with the Appium locator lesson. The classic way to reach a view is `findViewById<TextView>(R.id.headline)`. It searches the inflated hierarchy at runtime and has two weaknesses: - **No null safety.** If the id is not in the inflated layout (a typo, or a view that exists only in the landscape file), it returns `null` and the crash comes later. - **No type safety.** The caller decides the type; asking for an `ImageView` where the layout has a `TextView` fails with a `ClassCastException` at runtime. ## What view binding generates View binding is enabled per module in the module's build file: ```kotlin android { buildFeatures { viewBinding = true } } ``` The build then generates one **binding class per layout file**, named by converting the file name to Pascal case and appending `Binding`: `result_profile.xml` becomes `ResultProfileBinding`. Each class has: - a field for **every view with an id**, named in camel case (`user_bio` becomes `userBio`), typed to that view's class; - `root` (`getRoot()` in Java), the layout's root view; - static `inflate()` methods and a static `bind()` for a view that is already inflated. Views without an id get no field. A layout can opt out with `tools:viewBindingIgnore="true"` on its root. ## Using it in an activity and a fragment In an activity: 1. Call `ResultProfileBinding.inflate(layoutInflater)` in `onCreate()`. 2. Pass `binding.root` to `setContentView()`. 3. Use `binding.name.text = ...` from then on. In a fragment, inflate with `inflate(inflater, container, false)` in `onCreateView()` and return `binding.root`. The documentation's pattern keeps a nullable backing property and sets it to `null` in `onDestroyView()`, because **a fragment outlives its view**: when it goes to the back stack its view is destroyed while the fragment object stays, and a held binding would keep the whole old view tree in memory. The fragment and view lifecycles themselves are covered with activities and fragments. ## Layouts that differ between configurations A news screen may have `layout/` and `layout-sw600dp/` versions of the same file. View binding generates **one class** covering both: | Situation | Generated field | |---|---| | Id present in every configuration, same type | Non-null field of that type | | Id present only in some configurations | Field marked `@Nullable` (nullable in Kotlin) | | Id present everywhere with different types | Field of type `View`, unless `tools:viewBindingType` names a shared superclass | `tools:viewBindingType` must name a `View` subclass that is a superclass of the tag it sits on, and it must resolve to the same type in every configuration; view binding cannot validate it for you. ## View binding versus findViewById and data binding | | `findViewById` | View binding | Data binding | |---|---|---|---| | Null safety | No | Yes | Yes | | Type safety | No | Yes | Yes | | Annotation processing | None | None | Required | | Special `<layout>` tag | No | No | Yes | | Layout expressions, two-way binding | No | No | Yes | View binding is the lighter tool: faster builds and no changes to layout files. Data binding adds expressions in XML at the cost of annotation processing, and a project can use both in different layouts. ## Mistakes worth catching in review - **Keeping the fragment binding past `onDestroyView()`.** The code still compiles and mostly works, but every trip to the back stack keeps a dead view tree alive. - **Touching `binding` after the view is gone**, for example from a callback that fires late; with the `_binding!!` pattern this throws, which surfaces the bug instead of hiding it. - **Mixing `findViewById` and binding in one screen**, which brings the runtime null and cast failures back for the views reached the old way. - **Forcing a non-null access on a configuration-only field** with `!!`, which turns the nullable signal from view binding back into the crash it was meant to prevent. - **Expecting a field for a view without an id**: add `android:id` first, and the field appears on the next build.
- Why clear the binding in onDestroyView() instead of onDestroy()?A fragment on the back stack loses its view at `onDestroyView()` but the fragment object lives on. Holding the binding until `onDestroy()` keeps the destroyed view tree, with its bitmaps and listeners, in memory for that whole time.
- A view exists only in layout-sw600dp/. What does the binding expose on a phone?The field is generated as nullable because the view is missing from at least one configuration. On a phone it is `null`, so Kotlin forces a safe call, which is the compile-time version of the crash `findViewById` would have caused.
- When would you still choose data binding over view binding?When a layout needs layout variables, expressions in XML or two-way binding, which view binding does not support. You pay for it with annotation processing and `<layout>`-wrapped files, so many projects use data binding only in those layouts.
- View binding creates a field for every view, with or without an id.
- View binding requires wrapping each layout in a layout tag.
- A fragment can safely keep its binding until onDestroy.
- findViewById reports a wrong view type at compile time.
- View binding supports layout expressions just like data binding.