Understanding View Binding in Android

ViewBinding is a feature that allows you to more easily write code to interact with views in your XML layout files. It generates a binding class for each XML layout file present in your project. This binding class allows you to access all the views that are defined in that layout file directly from your code.

Enable View Binding in Build.gradle (Module:app)

Make sure the ViewBinding feature is enabled in your build.gradle file in the app module.

android {
    buildFeatures {
          viewBinding = true
    }
}

2. Create an XML Design
 

Set Up Layout Files

In your layout XML files, make sure to use the <layout> tag as the root element.

activity_main.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">
    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/NameET"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/enter_name"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/submitBTN"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/submit"
        android:layout_marginHorizontal="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/NameET"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

3. Accessing Views in Your Activity or Fragment

Once ViewBinding is set up, a binding class is automatically generated for each layout file. The class name is generated by converting the layout file name to camel case and appending "Binding" to it (e.g., ActivityMainBinding for activity_main.xml).

In your activity or fragment, you inflate the layout as usual, but instead of using findViewById, you use the generated binding class to access the views.

MainActvity.kt

package com.example.viewbinding
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.viewbinding.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        initUI()
    }
    private fun initUI() {
        binding.submitBTN.setOnClickListener {
            Toast.makeText(this, "submit is pressed", Toast.LENGTH_SHORT).show()
        }
    }
}

strings.xml

<resources>
    <string name="app_name">ViewBinding</string>
    <string name="enter_name">Enter Name</string>
    <string name="submit">Submit</string>
</resources>

Output

Output

Benefits of ViewBinding

  • Type Safety: ViewBinding provides compile-time safety for accessing views, reducing the likelihood of ClassCastException.
  • Null Safety: Since ViewBinding objects are created only after the view is inflated, there's no need for null checks on view references.
  • Performance: ViewBinding is more efficient than findViewById, as it accesses views directly through generated binding classes.

In summary, ViewBinding in Kotlin simplifies and streamlines the process of working with views in Android layouts, providing a more efficient and type-safe alternative to findViewById.


Similar Articles