Open In App

View Binding in Android Jetpack

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



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

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.




<?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.




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();
               }
             }
        });
    }
}




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:


Article Tags :