Open In App

View Binding in Android Jetpack

Last Updated : 18 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

View-Binding-in-Android-Jetpack


Features of View Binding

  1. 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.
  2. It works with both Java and Kotlin.
  3. 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.
  4. 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.xmlActivityMainBinding
    • Element IDs (Camel Case)
      • Example: android:id="button_submit"buttonSubmit
  5. 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:

<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:

design-ui-view-binding


Step 4: Working with the MainActivity file 

First, create the instance of the ViewBinding. We will be using Kotlin’s lazydelegation, 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

 Output:



Next Article

Similar Reads

three90RightbarBannerImg