View Binding | Android Studio | Java

Implementing View Binding in Android Studio

Intro:

The View binding is a feature that allows you to more easily write the 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. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.

From Android Studio 3.6, you can enable the View Binding that gives you the ability to replace findViewById with generated binding objects to simplify code, remove bugs, and avoid all the boilerplate of findViewById.

Check For Kotlin

How to enable ViewBinding?

The View Binding is enabled on a module by module basis. To enable the View Binding in a module, you need to set the ViewBinding build option to true in the module-level build.gradle file, as shown in the example:

android {
   ...
    buildFeatures {
       viewBinding true
    }
}

ViewBinding vs findViewById:

  • The findViewById is the source of many user-facing bugs in Android. E.g. It’s easy to pass an id that’s not in the current layout — producing null and a crash. And, since it doesn’t have any type-safety built in it’s easy to ship code that calls findViewById<TextView>(R.id.imageIv). View binding replaces findViewById with a concise, safe alternative that is ViewBinding.
  • ViewBinding is Type-safe because properties are always correctly typed based on the views in the layout. So if you put a TextView in the layout, view binding will expose a TextView property.
  • ViewBinding is Null-safe for layouts defined in multiple configurations. View binding will detect if a view is only present in some configurations and create a @Nullable property.

ViewBinding - Activity

Let's check how to implement ViewBinding in an Activity.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="#f7f7f9"
    android:padding="20dp"
    tools:context=".MainActivity">

    <!--Title-->
    <TextView
        android:id="@+id/titleTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ViewBinding - Activity"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="20sp" />

    <!--Description-->
    <TextView
        android:id="@+id/descriptionTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text=""
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="16sp" />

    <!--Click to open/show fragment-->
    <Button
        android:id="@+id/showDescriptionBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/button_color"
        android:text="Show Storage"
        android:textColor="@color/white" />

</RelativeLayout>

MainActivity.java

package com.blogspot.atifsoftwares.viewbinding;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.blogspot.atifsoftwares.viewbinding.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    //ViwBinding. activity_main ==> ActivityMainBinding
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //change text activityTitleTv
        binding.titleTv.setText("The Title");

        //handle button click
        binding.showDescriptionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //change text of descriptionTitleTv
                binding.descriptionTv.setText("The button is clicked and the description is shown...");
            }
        });

    }
}

ViewBinding - Fragment

Let's check how to implement ViewBinding in a fragment.

fragment_my.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="#f7f7f9"
    android:padding="20dp"
    tools:context=".MyFragment">

    <!--Title-->
    <TextView
        android:id="@+id/titleTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ViewBinding - Fragment"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="20sp" />

    <!--Description-->
    <TextView
        android:id="@+id/descriptionTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text=""
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="16sp" />

    <!--Click to open/show fragment-->
    <Button
        android:id="@+id/showDescriptionBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/button_color"
        android:text="Show Storage"
        android:textColor="@color/white" />

</RelativeLayout>

FragmentMy.java

package com.blogspot.atifsoftwares.viewbinding;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

import com.blogspot.atifsoftwares.viewbinding.databinding.FragmentMyBinding;

public class MyFragment extends Fragment {

    //ViewBinding. fragment_my ==> FragmentMyBinding
    private FragmentMyBinding binding;

    public MyFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentMyBinding.inflate(inflater, container, false);


        //change text activityTitleTv
        binding.titleTv.setText("The Title");

        //handle button click
        binding.showDescriptionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //change text of descriptionTitleTv
                binding.descriptionTv.setText("The button is clicked and the description is shown...");
            }
        });

        return binding.getRoot();
    }


}

ViewBinding - Dialog

Let's check how to implement ViewBinding in an Activity.

dialog_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">
    
    <TextView
        android:id="@+id/dialogTitleTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="View Binding - Dialog"
        android:textSize="20sp"
        android:padding="20dp"
        android:textColor="@color/black"
        android:textAlignment="center"/>

    <TextView
        android:id="@+id/dialogDescriptionTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textColor="@color/black"
        android:textAlignment="center"
        android:text="Tutorial for implementing ViewBinding in the Activity, Fragment, Dialog, Custom Layout etc."
        android:layout_centerInParent="true"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true">

        <Button
            android:id="@+id/dialogOkBtn"
            android:text="OK"
            android:layout_weight="1"
            android:background="@color/button_color"
            android:textColor="@color/white"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>


        <Button
            android:id="@+id/dialogCancelBtn"
            android:text="Cancel"
            android:layout_weight="1"
            android:background="@color/button_color"
            android:textColor="@color/white"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </LinearLayout>

</RelativeLayout>

Code - Java:

private DialogLayoutBinding layoutBinding;

    private void openAlertDialog() {
        //inflate layout using ViewBinding (for Alert Dialog)
        layoutBinding = DialogLayoutBinding.inflate(LayoutInflater.from(this));

        //Alert Dialog builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //set layout
        builder.setView(layoutBinding.getRoot());

        //Alert Dialog, create, show
        AlertDialog dialog = builder.create();
        dialog.show();

        //handle click
        layoutBinding.dialogOkBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
                //dismiss dialog
                dialog.dismiss();
            }
        });
        layoutBinding.dialogCancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Cancel", Toast.LENGTH_SHORT).show();
                //dismiss dialog
                dialog.dismiss();
            }
        });
    }


View Binding | Android Studio | Java


Comments

Popular posts from this blog

Picture In Picture | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Kotlin

Add a Back Button to Action Bar Android Studio (Kotlin)