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.
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 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 vs Kotlin Synthetics:
- The Synthetics let you replace calls to findViewById with kotlinx.android.synthetic bindings.
- Parcelize allows you to remove boilerplate and easily create Parcelables through the @Parcelize annotation.
ViewBinding - 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.wongngaur.myapplication
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.wongngaur.blogspot.myapplication.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
//ViwBinding. activity_main ==> ActivityMainBinding
private var binding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding!!.root)
//change text activityTitleTv
binding!!.titleTv.text = "The Title"
//handle button click
binding!!.showDescriptionBtn.setOnClickListener {
//change text of descriptionTitleTv
binding!!.descriptionTv.text = "The button is clicked and the description is shown..."
}
}
}
ViewBinding - 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.wongngaur.myapplication
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.wongngaur.blogspot.myapplication.databinding.FragmentMyBinding
class MyFragment : Fragment() {
//ViewBinding. fragment_my ==> FragmentMyBinding
private lateinit var binding: FragmentMyBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
binding = FragmentMyBinding.inflate(inflater, container, false)
//change text activityTitleTv
binding.titleTv.text = "The Title"
//handle button click
binding.showDescriptionBtn.setOnClickListener { //change text of descriptionTitleTv
binding.descriptionTv.text = "The button is clicked and the description is shown..."
}
return binding.root
}
}
ViewBinding - Dialog
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 lateinit var layoutBinding: DialogLayoutBinding
private fun openAlertDialog() {
//inflate layout using ViewBinding (for Alert Dialog)
layoutBinding = DialogLayoutBinding.inflate(LayoutInflater.from(this))
//Alert Dialog builder
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
//set layout
builder.setView(layoutBinding.root)
//Alert Dialog, create, show
val dialog: AlertDialog = builder.create()
dialog.show()
//handle click
layoutBinding.dialogOkBtn.setOnClickListener {
Toast.makeText(this@MainActivity, "OK", Toast.LENGTH_SHORT).show()
//dismiss dialog
dialog.dismiss()
}
layoutBinding.dialogCancelBtn.setOnClickListener {
Toast.makeText(this@MainActivity, "Cancel", Toast.LENGTH_SHORT).show()
//dismiss dialog
dialog.dismiss()
}
}