How to use viewBinding in Kotlin to replace findViewById<>()?

  • Post last modified:April 27, 2021
  • Reading time:2 mins read

Hey Android Folks! If you frustrate to use findViewById<>() every time to hook up with all the resources of the respective activity

You have to mention type of view and there resource id name .

If you made some mistake then ready for getting null error

To easy life from Android 4.0 studio you do not need to type old school findViewById<>()

Before 4.0 also these features were there but now the interesting thing is now you do not need to make any changes to your XML file.

How to enable viewBinding?

Gradle

To enable viewBinding you have to open build.gradle(:app) in this you have to add

buildFeatures {
viewBinding true
}

in like this way below android

After this Sync Gradle file,viewBinding will generate binding class for all the layout automatically

Then back to Activity File over here you have to make few changes

Activity

We first initialize the ActivityMainBuilding this file contain all the resource id name, If you are activity name is activity_main.xml now it will convert automatically to ActivityMainBuilding

private lateinit var binding: ActivityMainBinding

Now below to savedInstanceState assign binding variable to inflate layout

binding = ActivityMainBinding.inflate(layoutInflater)
Applied ViewBinding
Applied ViewBinding

In setContentView replace the activity_main.xml to binding.root

setContentView(binding.root)

First, call the binding variable then resource name in this case I have used Button which id is given doneButton.

Now you can run this app to check

In this way, you can replace to use of findViewById<>() and use viewBinding.

Read this: How to install WSL2 in windows 10?

Like what you read? Please share it with others.
guest
0 Comments
Inline Feedbacks
View all comments