Practice English Speaking&Listening with: Android Jetpack: Replace findViewById with view binding

Difficulty: 0

SEAN MCQUILLAN: Use the new view binding library to replace

findViewById in your app.

It lets you write concise, safe code, with less boilerplate.

Instead of having to look up every view,

it generates a binding object that

holds all the views for you.

View binding adds safety.

When you inflate a view, the binding object

will automatically give you the right type.

In this example, the greeting is automatically a text view.

And if the view is only present in landscape,

the binding will be nullable.

This helps you avoid crashing in production.

And what's really cool is, you can use view binding

in both Kotlin and the Java programming language.

Let's dive in and see how to use it in your app.

View binding requires Android Studio and the Android Gradle

plugin, 3.6 or higher.

To use it in your module, enable it in your build.gradle file.

You don't need to include any libraries to use view binding.

When you enable the compiler, it will automatically

recompile your project and generate binding objects

for every layout.

So if you have a layout file called activity_main.xml,

view binding will generate a small class called


It will have one correctly typed and null-safe property

for every view with an ID in the layout.

Then, in your activity, instead of inflating the layout

directly, you can use the inflate method

on ActivityMainBinding.

It'll inflate the layout for you and return a binding object

with all views bound.

The layout for your activity is stored in a special property

called root.

So you can call setContentView(binding.root).

And that's really all you need to know to get

started with view binding.

It's really that simple.

And it's a lot safer and more concise than findViewById.

If you like view binding and want

to take it a step further to bind views declaratively,

consider taking a look at the data binding

library, which gives you the ability

to automatically bind views.

Go ahead and try it on your modules today.

We'd love to hear your feedback.

Thanks for watching.

Be sure to like and subscribe to learn more

about Android development.


The Description of Android Jetpack: Replace findViewById with view binding