View Binding in Android Jetpack
Last Updated :
18 Feb, 2025
View Binding is one of the best features in Android that allows views to bind seamlessly with an ongoing activity. It replaces the traditional findViewById()
method, significantly reducing boilerplate code by automatically generating instances of views for the current layout. One of its most important advantages is that View Binding is always null-safe, ensuring safer and more efficient code.
Features of View Binding
- Null Safe and Type Safe - View Binding ensures that all references to views are null-safe and type-safe, making development more secure and reducing runtime crashes.
- It works with both Java and Kotlin.
- Less Boilerplate code - With the use of view binding, we do not need to manually use the findViewById() method for every views, making it easy to maintain and reducing a lot of redundant code.
- Follows Naming Conventions - View Binding generates a binding class based on the name of the XML layout file. This improves code readability and ensures consistent naming across the project. The naming conventions follow:
- Snake Case (XML file) → Pascal Case (Binding class)
- Example:
activity_main.xml
→ ActivityMainBinding
- Element IDs (Camel Case)
- Example:
android:id="
button_submit
"
→ buttonSubmit
- Faster Compilation - View Binding makes the compilation process faster compared to the
findViewById()
method, improving efficiency.
Ignoring a Layout in View Binding
If a particular layout should be ignored by View Binding, this can be done by adding the following attribute to the root layout XML:
tools:viewBindingIgnore="true"
This ensures that View Binding does not generate a binding class for that specific layout.
Step by Step Implementation
Step 1: Create an empty activity project
Here Android Studio is used, refer to Android | How to Create/Start a New Project in Android Studio, to know how to create an empty activity Android Studio project.
Step 2: Enabling the ViewBinding Feature
Navigate to Gradle Scripts > build.gradle.kts (Module :app) file and add the following code anywhere under the android {} scope.
android {
buildFeatures {
viewBinding = true
}
}
Step 3: Working with the activity_main.xml file
The main layout of the file contains one EditText and one Button. To implement the same UI invoke the following code inside the actitvity_main.xml file.
actitvity_main.xml:
XML
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_marginTop="32dp"
android:src="@drawable/gfg_logo"
app:layout_constraintBottom_toTopOf="@+id/editText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:hint="Enter Something"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="@+id/editText"
app:layout_constraintStart_toStartOf="@+id/editText"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
Design UI:
Step 4: Working with the MainActivity file
First, create the instance of the ViewBinding. We will be using Kotlin's lazy
delegation, which means the binding
property is initialized only when it's accessed for the first time.
private val binding: ActivityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
Setting the root view from binding
setContentView(binding.root)
Accessing the properties of the layout goes as follows.
binding.submitButton
Invoke the following code inside the MainActivity.kt/MainActivity.java file, comments are added for better understanding.
MainActivity.java
package org.geeksforgeeks.demo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.geeksforgeeks.demo.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize View Binding
binding = ActivityMainBinding.inflate(LayoutInflater.from(this));
setContentView(binding.getRoot());
binding.submitButton.setOnClickListener(view -> {
String inputText = binding.editText.getText().toString();
if (!inputText.isEmpty()) {
Toast.makeText(this, "You entered " + inputText, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter something", Toast.LENGTH_SHORT).show();
}
});
}
}
MainActivity.kt
package org.geeksforgeeks.demo
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.geeksforgeeks.demo.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val binding: ActivityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.submitButton.setOnClickListener {
val inputText = binding.editText.text.toString()
if (inputText.isNotEmpty()) {
Toast.makeText(this, "You entered $inputText", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Please enter something", Toast.LENGTH_SHORT).show()
}
}
}
}
Output:
Similar Reads
View Binding with Fragments in Android Jetpack
In the Previous article View Binding in Android Jetpack, it's been discussed why acquiring the ViewBinding feature in the Android project provides a lot of benefits. But when it comes to ViewBinding with fragments the scenario changes. Because the lifecycle of the Fragment is different and that of a
6 min read
Synthetic Binding in Android
In android application development, for every view in the XML, we need to get an instance of that view to get access to it for doing any operation on it, like changing any property of a view. This is a very common requirement in any android application development cycle. There are main two ways of a
3 min read
Slider in Android Jetpack
Jetpack Compose in Android has brought a modern and streamlined approach to building UI components inside an Android Application. One of its components is 'Slider'. It provides a way for users to select a value between a certain range by dragging their finger on a horizontal line. Sliders are perfec
6 min read
Building UI Using Jetpack Compose in Android
Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will
7 min read
Introduction to Android Jetpack
The Android support libraries are used in almost all android applications to overcome the compatibility issues across different Android OS versions and devices. These libraries also facilitate users to add various kinds of updated widgets in the application. Over time, these libraries are updated ac
6 min read
Jetpack Navigation Component in Android
The Navigation Architecture Component simplifies navigation implementation while also assisting you in visualizing your app's navigation flow. The library offers a variety of advantages, including:Handling of fragment transactions automaticallyBy default, up and back actions are handled correctly.De
4 min read
WebView in Android using Jetpack Compose
In Android, a WebView is an extension of View Class that allows us to display webpages. In simpler words, if you want to display a webpage in Activity Layout, then you can implement a WebView to display it. It is very similar to a browser but isn't one. A WebView can rather be referred to as a show
2 min read
Change Button Size in Android Jetpack Compose
In Android, Button is a very common UI element that is used to call a function or perform a task when clicked by the user. A Button by default occupies specific space depending upon the text that it displays. If the Button text is longer or has a larger font size, the Button width, and height increa
3 min read
Jetpack DataStore in Android
Jetpack DataStore is a data storage solution that uses protocol buffers to store key-value pairs or typed objects. DataStore stores data asynchronously, reliably, and transactionally using Kotlin coroutines and Flow. In this article, we will look at why we need Jetpack DataStore Preferences, how to
5 min read
Android WebView in Kotlin
WebView is a view that is used to display web pages inside the app. It is used to turn the app into a web application. In this article let's display the https://www.geeksforgeeks.org/ inside the Android Application using Kotlin. Note: To implement Android WebView in Java please refer How to use WebV
2 min read