Sitemap

Android viewbinding

2 min readMar 3, 2023

--

Hello and welcome to this post on Android ViewBinding.

As Android developers, we often use findViewById() method to access views in our layout files. However, this method can be error-prone, time-consuming, and difficult to read and maintain. ViewBinding is a new feature in Android that simplifies the process of accessing views in our layouts.

ViewBinding generates a binding class for each layout file in our project. This class contains direct references to all the views in the layout file, which we can access without the need for findViewById() method. This improves the readability, performance, and type-safety of our code.

Here’s how you can use ViewBinding in your Android project:

Step 1: Add ViewBinding to your build.gradle file

In your app’s build.gradle file, add the following code:

android {
...
buildFeatures {
viewBinding true
}
}

Step 2: Create a binding object

Get Rajeev Mathur’s stories in your inbox

Join Medium for free to get updates from this writer.

In your activity or fragment, create a binding object for your layout file using the following code:

For Activity:

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}

For Fragment:

private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}

override fun onDestroyView() {
super.onDestroyView()
_binding = null
}

Step 3: Access your views using the binding object

Now that you have created a binding object, you can access your views using the binding object. For example, if you have a TextView with an ID of “textView” in your layout file, you can access it using the following code:

binding.textView.text = "Hello, World!"

And that’s it! ViewBinding is a powerful and convenient way to access views in your Android project. It saves time and reduces the likelihood of errors in your code.

Thanks for reading this post on Android ViewBinding. I hope you found it helpful!

--

--

Rajeev Mathur
Rajeev Mathur

Written by Rajeev Mathur

I am an Android developer specializes in creating applications for the Android operating system using programming languages Java and Kotlin.