View Binding

View Binding in Android with Example

In this article, We’ll learn about View Binding in detail with suitable Examples in Android, and several scenarios in which it could be useful. In the end, you will have a clear understanding of this commonly used technology.

View binding allows you to replace findViewById with generated binding objects in order to simplify code, eliminate bugs, and avoid all of the boilerplates of findViewById(). It is used to make working with views extremely simple and reduces a lot of boilerplate code, making it very simple to work with views and perform operations on them.

Enable View Binding

To enable view binding in a module, set the View Binding to build option to true in the build.gradle(Module), as shown in the following example:

android {
    ...
    buildFeatures {
        viewBinding = true
    }
}

Add the tools: if you want a layout file to be ignored when generating binding classes. viewBindingIgnore=”true” attribute to the layout file’s root view:

<LinearLayout
        ...
        tools:viewBindingIgnore="true" >
    ...
</LinearLayout>

Advantages of View Binding

  • ViewBinding supports both Java and Kotlin and is always null safe and type-safe.
  • Gradle version 3.6 and higher introduce ViewBinding (which comes with the Android Studio 4.0, only gradle 3.6).
  • ViewBinding also helps in the reduction of boilerplate code, hence reducing code repetition.
  • Because it builds the binding class internally using the name of the same layout file, proper naming rules must be followed while using ViewBinding. It’s best to name the layout file in the snake case. For example, ViewBinding creates the ActivityMainBinding(pascal case) file, which contains all the properties and instances of all the views in that layout.
  • Moreover, whatever IDs of all elements are created inside the layout XML file, ViewBinding allows for better code compilation than the standard findViewById() approach.

Difference between View Binding and Data Binding

View BindingData Binding
When view binding in an android project module is enabled It generates a binding class for the layout file that contains a direct reference to those views as well as the id assigned to them in the XML layout. Which can then be used instead of creating a variable for it and then casting it with findViewById.

It is used to make working with views extremely simple and reduces a lot of boilerplate code, making it very simple to work with views and perform operations on them.
The Data Binding Library is an Android Jetpack library that allows you to bind UI components in your XML layouts to data sources in your app using a declarative format rather than programmatically, reducing boilerplate code. It can be categorized into 2 types i.e.

1: One-Way binding
2: Two-Way binding
View Binding

Using view binding in activities

To create an instance of the binding class for use with an activity, perform the following steps in the onCreate() method of the activity:

  • Invoke the static inflate() method from the generated binding class. This creates a binding class instance for the activity to use.
  • Call the getRoot() method or use Kotlin property syntax to obtain a reference to the root view.
  • Set the active view on the screen bypassing the root view to setContentView().
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
}

Using view binding in fragments

To create a binding class instance for use with a fragment, perform the following steps in the fragment’s onCreateView() method:

  • Invoke the static inflate() method from the generated binding class. This creates a binding class instance for the fragment to use.
  • Call the getRoot() method or use Kotlin property syntax to obtain a reference to the root view.
  • To make the active view on the screen, return the root view from the onCreateView() method.
private var _binding: FragmentBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentBinding.inflate(inflater, container, false)
    val view = binding.root
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}
   

Working with View Binding Example

Get Started

Step 1: To start with View Binding:  To enable view binding in a module, set the View Binding option to true in the build.gradle(Module), as shown in the following example:

android {
    ...
    buildFeatures {
        viewBinding = true
    }
}

Step 2: In activity_main.xml add textView and Button.

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="35sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.482"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.099" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="548dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

Step : 3 In the MainActivity file invoke the static inflate() method from the generated binding class. This creates a binding class instance for the activity to use. Call the root() method to obtain a reference to the root view. Set the active view on the screen bypassing the root view to setContentView().

package com.sagar.viewbinding

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.sagar.viewbinding.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        binding.textView.text = "View Binding Example"

        binding.button.setOnClickListener {
            Toast.makeText(this,"Developers Dome",Toast.LENGTH_SHORT).show()
        }
    }


}

Run the application now. You will get the output shown in the output section.

Output:

 View Binding Example

That’s all about the View Binding in Android.

If you are interested in learning Data binding, you can go through Data Binding in Android with Example, here I have explained Data Binding, One-way, and Two-way Data Binding, @BindingAdapter in detail with suitable Examples in Android, and several scenarios in which data binding can be useful. and I assure you that by the end, you will have a clear understanding of this commonly used method.

What to choose between View Binding and Data Binding?

If we look at the question we started with, “View Binding or Data Binding,” the better response is that it truly depends on your usage, but if you had to ask me to choose one for you, consider the following scenarios. View Binding should be sufficient for a smaller project with supposedly like 2-4 screens while keeping the project clean and clear. Also, if you are a beginner, use View Binding to get started and then move on to Data Binding for a project that is larger than that, such as 4-5 screens or more, go with Data Binding because this will really cut down on the complexity and development time.

We hope that this guide will assist you in understanding all the concepts of View Binding in android. We have concentrated on making basic, meaningful, and easy-to-learn concepts of View Binding with suitable examples. Still, if you have any problems regarding View binding, please post them in the comments section, we will be glad to assist you.

This Post Has 2 Comments

Leave a Reply