Open In App

View Binding in Android Jetpack

Last Updated : 28 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

View Binding is one of the best features which provides the views to bind with the activity which is ongoing. Replacing the findViewById() method, hence reducing the boilerplate code, generated the instances of the views of the current layout. And most important feature about the View Binding is it’s always null safe. In this article detailed it’s been provided in detail approach for the View Binding.

View Binding Features in Android

  • ViewBinding is always null-safe and type-safe, which supports both Java and Kotlin.
  • ViewBinding is introduced in Gradle version 3.6 and above (which comes with Android Studio 4.0, only Gradle 3.6).
  • ViewBinding also helps to reduce the boilerplate code, hence reducing the code redundancy.
  • While using ViewBinding proper naming conventions need to be followed because it creates the binding class internally using the name of the same layout file. Naming the layout file in the snake case is preferred. For Example, ViewBinding creates an activity_main.xml(snake case) file as ActivityMainBinding(pascal case), which contains all the properties and instances of all the views contained in that layout.
  • And also whatever IDs of all elements are created inside the layout XML file, the ViewBinding converts them to camel case. For example android:id=”button_submit” -> buttonSubmit. Which is much useful in code readability.
  • Using ViewBinding the compilation of the code is a bit faster as compared to the traditional findViewById() method.
  • The ActivityMainBinding class is generated in the following path under the project hierarchy this can be viewed.

  • The following is the flow of how the objects of the properties from the layout are generated.

View Binding in Android Jetpack

  • However, if the layout has to be ignored with the binding the views of it, can be done by adding the following attribute to the root layout.

tools:viewBindingIgnore=”true”

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

  • There is a need to enable the ViewBinding feature in Android Studio 4.0 and above, inside the app-level build gradle file.
  • Invoke the following code snippet inside the android{} body of the gradle file.

buildFeatures {

       viewBinding = true

}

  • Refer to the following image if unable to locate the app-level gradle file and invoke the feature under the project view hierarchy.

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.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
 
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="128dp"
        android:layout_marginEnd="16dp"
        android:hint="Enter Something"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/buttonSubmit"
        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_constraintTop_toBottomOf="@+id/editText" />
 
</androidx.constraintlayout.widget.ConstraintLayout>


 Output UI:

Step 4: Working with the MainActivity file 

The things that need to be focused on here are, creating the instance of the ViewBinding. Following is the code snippet which is used to create an instance.

var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)

which may under global or local scope according to the usage.

Accessing the properties of the layout goes as follows.

binding.camelCaseConvertedObject

Invoke the following code inside the MainActivity.kt/MainActivity.java file, comments are added for better understanding.

Java




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding
 
public class MainActivity extends AppCompatActivity {
     // calling binding class for activity_main.xml
     // which is generated automatically.
     ActivityMainBinding activityMainBinding;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         
        // inflating our xml layout in our activity main binding
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
         
        // getting our root layout in our view.
        View view = activityMainBinding.getRoot();
        
        // below line is to set
        // Content view for our layout.
        setContentView(view);
 
        // calling button and setting on click listener for our button.
        // we have called our button with its id and set on click listener on it.
        activityMainBinding.buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               String str = activityMainBinding.editText.getText().toString();
               if(str.isEmpty()) {
               Toast.makeText(this, "Please enter something", Toast.LENGTH_SHORT).show();
               } else {
               Toast.makeText(this, "You entered " + activityMainBinding.editText.geText().toString(), Toast.LENGTH_SHORT).show();
               }
             }
        });
    }
}


Kotlin




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding
 
class MainActivity : AppCompatActivity() {
 
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
 
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.buttonSubmit.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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads