TheJadav

Android view binding vs data binding

In this blog we are going to see difference between view binding and data binding in Android application development. But first of all we need check individually what they are and how they arr working?

In this blog we are going to see difference between view binding and data binding in Android application development. But first of all we need check individually what they are and how they arr working?

View binding

View binding is a feature by which we can interact with view easily. We can enable view binding for each module, once it is enabled it generates binding class for each xml layout file presents in that module. An instance of binding class contains direct reference to all views by view ID. Now we have enough theory about view binding so let’s check how we can enable it.

Setup view binding

To enable view binding for a module we need to define it within the build.gradle file like below:

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

Use view binding

Now binding class must be generated so you are good to access view into activity of fragment. Lets see how binding class generated.

Here I have sample file named result_profile.xml 

<LinearLayout ... >
    <TextView android:id="@+id/name" />
    <ImageView android:cropToPadding="true" />
    <Button android:id="@+id/button"
        android:background="@drawable/rounded_button" />
</LinearLayout>

Generated binding class will be ResultProfileBinding. We have two IDs name and button, so we got two reference. ImageView don’t have ID so it will not have reference. 

Use view binding in Activity

Below code will show you how to use view binding in Activity

private lateinit var binding: ResultProfileBinding

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

Use view binding in Fragment

Below code will show you how to use view binding in fragment

private var _binding: ResultProfileBinding? = 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 = ResultProfileBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

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

Let’s check each code in details. Binding class has inflate() method which is static method to create instance of view which can be used in activity or fragment.

You can also use bind() method is layout is already inflated. Second thing you can notice is root, which is method from Binding class. getRoot() method contains reference to main layout from the xml layout. 

So now we need to pass that binding.root into onCreateView() or setContentView() according to our usage.

Data Binding

To use data binding we need to enable data binding in build.gradle file which preety similar to view binding

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

Note here, data binding already contains view binding, so it is view + data binding. Same binding class will be generated when using data binding. But now you have some additional benefit, like you can assign variable from within xml file, see below

<TextView
    android:text="@{viewmodel.userName}" />

See here, how to create variable in xml file

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="viewmodel"
            type="com.myapp.data.ViewModel" />
    </data>
    <ConstraintLayout... /> <!-- UI layout's root element -->
</layout>

This type of declaration or facility is called expression language.

So now your layout capable to observe your obeservables. Like you have title variable with data type Livedata<> or MutableLivedata<>, your text in xml file will be automatically change when you change value for that variable from viewModel class.

Remember to assign lifecycleOwner to your binding class to get live updates to layout file. 

Two way data binding

Yes you heard it right, it is two way. What it mean by two-way?

Let’s understand it by simple example. You have EditText in layout and variable in viewModel class. 

<EditText
    android:id="@+id/birth_date"
    android:text="@={viewmodel.inputString}"
/>

Check above example. From viewmodel you can assign text to inputString variable which can update EditText directly and user can input text from UI and it will automatically update value of inputString variable.

Please remeber always refer official document to get exact idea about any feature, here I have link for DataBinding and ViewBinding. So we are good to identify difference between them.

DataBindig vs ViewBinding

They both have thair advantages and disadvantages, see below in details.

  1. View binding have faster compilation, hence it is for simple use cases
  2. View binding dont require specially tagged xml files, so it is faster to adopt.
  3. Data binding supports layout variables or layout expresions, while view binding doesn’t.
  4. You can create two-way data binding, which is advantage over view binding.

Share this content:

Share:

More Posts

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message