Learn basic View binding in 5 mins, The easiest way!

Pavitra Raut
2 min readApr 2, 2021
Cover image

Introduction

Hey fellow developers, this is Pavitra again in my new post where I will be showing you View Binding feature.

When View Binding is enabled, it auto generates binding files for each XML with the same name as XML file in Pascal case and ‘Binding’ keyword at the end of the file name and this auto generated file is used to access the views.

I know it sounds complex 🤯 but it is not, so that is it for the intro, let’s start with actual post.

Advantages

First of all let’s see what advantages does View binding comes with:

  • Faster than Data Binding and Butterknife as it does not uses Annotation processing.
  • Null-safety as we do not need to explicitly initialize.
  • Compile-time safety out of the box.

Enabling

As we have seen View Binding comes with lots of goodies let’s learn how to enable it.

So to enable it, you’ll need Android Studio 3.6 or above. Now go to your build.gradle(app level) file and add below lines

build.gradle (app level) (code snippet)

That is it, View Binding is enabled now and no other libraries are needed to enable it 😁.

Usage

Now that we have enabled View Binding let’s see how to use it.

In Activity

To use binding in activity you have to first inflate the layout then set it as content view. Then use the layout instance to bind the views as shown in example.

MainActivity.kt (code snippet)

In Fragment

It’s similar to Activity but just few extra params. In case of DialogFragment also it is similar. One important thing is to release the layout instance to avoid memory leak so we are going to make it null.

MainFragment.kt (code snippet)

In Adapter

Similar to Fragment but for adapter we have to use ViewHolder to bind the views.

Adapter.kt (code snippet)

Outro

You’re are a great reader if you are still reading this post and specially for you guys, I’ve got you some bonus stuffs. I’ve included base classes for Activity and Fragment which helps you using View Binding in a more easier way or you can just refer to it and create your own Base/Helper class.

That’s it for this post. Thanks for reading.

--

--