View Binding in Android Jetpack - GeeksforGeeks

24 May, 2021
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.
ViewBinding is always null safe and type-safe, which supports both Java and Kotlin.
ViewBinding is introduced in the Gradle version 3.6 and above (which comes with the Android Studio 4.0, only gradle 3.6).
ViewBinding also helps to reduce the boilerplate code, hence reducing the code redundancy.
While using the ViewBinding proper naming conventions are 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, the ViewBinding creates activity_main.xml(snake case) file as ActivityMainBinding(pascal case), which contains all the property and instances of all the views containing 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 the 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.
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 1: Create an empty activity project
Here the 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 enabling 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: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"    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/button"        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.
 
Kotlin
Java
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() {     // create instance of the ActivityMainBinding,    // as we have only one layout activity_main.xml    private lateinit var binding: ActivityMainBinding     override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)         // create instance of the ActivityMainBinding,         // as we have only one layout activity_main.xml        var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)         // binding.root returns the root layout,        // which is activity_main.xml file itself        setContentView(binding.root)         // using the binding variable we can access the layout        // properties and perform the operations on them as usual        binding.buttonSubmit.setOnClickListener {            val str: String = binding.editText.text.toString()            if (str.isNotEmpty()) {                Toast.makeText(this, "You entered " + binding.editText.text.toString(), Toast.LENGTH_SHORT).show()            } else {                Toast.makeText(this, "Please enter something", Toast.LENGTH_SHORT).show()            }        }    }}
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport 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();               }             }        });    }}
  
 
chaitanyamunje
anikaseth98
Android-Jetpack
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Resource Raw Folder in Android Studio
Broadcast Receiver in Android With Example
Services in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android UI Layouts
Kotlin Array
Services in Android with Example
Android RecyclerView in Kotlin