Android ViewBinding

 

View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module.

In most cases, view binding replaces findViewById

To enable view binding in a module, set the viewBinding build option to true in the module-level build.gradle file, as shown in the following example:

 

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.vision.infotech.jetpackviewbinding"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildFeatures {
        viewBinding = true
    }

}

If view binding is enabled for a module, a binding class is generated for each XML layout file that the module contains. Each binding class have references to the root view and all views that have an ID. The name of the binding class is generated by converting the name of the XML file to Pascal case and adding the word “Binding” to the end.

For example, given a layout file called activity_main.xml:

Generated Binding class name : ActivityMainBinding

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

    <EditText
        android:id="@+id/editTextTextEmailAddress3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_margin="10dp"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:layout_constraintVertical_bias="0.25" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.16000003"
        tools:srcCompat="@tools:sample/avatars" />

</androidx.constraintlayout.widget.ConstraintLayout>

Every binding class also includes a getRoot() method, providing a direct reference for the root view of the corresponding layout file. In this example, the getRoot() method in the ActivityMainBinding class returns the Constraintlayout root view.

  1. First Create reference of ActivityMainBinding class by using ActivityMainBinding.inflate(getLayoutInflater());
  2. Now we can get root view of our xml file by using mainActivityBinding.getRoot() and pass it to set contentview(); and it will inflate our activity xml file on screen
  3. Now from mainActivityBinding reference we can directly access our all available view in our xml file, in this case in our layout we have one edit text and one image view.
  4. Now we can set data on our view as follow.
public class MainActivity extends AppCompatActivity {

    ActivityMainBinding mainActivityBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainActivityBinding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = mainActivityBinding.getRoot();
        setContentView(view);

        setViewData();
    }

    private void setViewData(){
        mainActivityBinding.imageView2.setImageDrawable(getResources().getDrawable(R.drawable.download));
        mainActivityBinding.editTextTextEmailAddress3.setText("https://visioninfotech.net/");
    }

}
  • Null safety: Since view binding creates direct references to views, there’s no risk of a null pointer exception due to an invalid view ID.
  • Type safety: The fields in each binding class have types matching the views they reference in the XML file. This means that there’s no risk of a class cast exception.

https://github.com/Rutvik-vision-403/JetpackViewBinding

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories