Why Data binding?
Actually creating views in XML and then finding them in JAVA or KOTLIN file after that applying the data sources on those views is kind of overhead to the developers.
What is data binding?
Data binding is an android support library to bind UI components(view or ViewGroup) in your layout to data sources in your app using declarative way rather that programmatically way(kind of overhead to the developers)
Data binding allows to synchronize your User Interface with your application model and the Logic.
This is a part of the data binding series. The next parts are:
- Binding Adapters in data binding
- Two-Way Data Binding
Ways of data binding in android
One Way data binding
One way data binding is Unidirectional, it means flow of code is like data is coming from data source and inflating over UI.
android:text='@{news.title}'
Two Way data binding
Two way data binding is bidirectional, it mean flow of code is from UI event to data and throwback to UI immediately with result.
android:text='@={viewmodel.inputName}'
Usage of Data binding
Step 1: Add dependency in build.gradle(:app) file
buildFeatures{ dataBinding true }
Step 2: Create your UI and use layout, data, variable tags from data source.
Important: If you had not synced your project or somehow the dataBinding is not enabled in your project then you will not able to see below option to convert the layout into Data binding layout.
After applying data binding your XML view will be like below Snippet
Let’s implement a simple news view
<?xml version="1.0" encoding="utf-8"?> <layout 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"> <data> <variable name="viewmodel" type="com.example.newsapp.newsviewmodel" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/txtTitle" android:layout_width="match_parent" android:layout_height="match_parent" android:text='@{viewmodel.title}' android:textColor="@color/black" android:textSize="20sp" tools:text="test title" /> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
Binding data at the activity level
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding // create and initialze view model object private val dogViewModel: DogViewModel by ViewModelLazy( DogViewModel::class, { viewModelStore }, { defaultViewModelProviderFactory } ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding= ListItemBinding.inflate(layoutInflater) // or // binding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false) binding.apply { lifecycleOwner = this@MainActivity } initViews() setUpObservers() } private fun setUpObservers() { dogViewModel.dogResponse.observe(this) { binding.dogResponse = it } } }
you can check out that what android developer documentation says about data binding here
A few more things like:
How to use button action using data binding?
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:onClick="@{() -> viewModel.onButtonClick()}" />
How to use images with data binding?
Binding Adapters are a powerful feature of Android’s Data Binding library that allow you to define custom attributes and behaviors for views directly in your layout XML. This can help you encapsulate complex view logic and keep your UI code clean and organized.
import android.widget.ImageView; import androidx.databinding.BindingAdapter; import com.squareup.picasso.Picasso; public class BindingAdapters { @BindingAdapter("imageUrl") public static void loadImage(ImageView view, String imageUrl) { Picasso.get().load(imageUrl).into(view); } }
Or
@BindingAdapter("imageFromUr1") fun ImageView.imageFromUr1(ur1 :string){ Glide.with(this.context).load(url).into(view:this) }
Apply the Binding Adapter in Layout XML:
In your layout XML, you can now use the
imageUrl attribute with the ImageView:<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="viewModel" type="com.example.YourViewModel" /> <variable name="url" type="string" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" app:imageUrl="@{viewModel.imageUrl}" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" imageFromUrl="@{url}" /> </LinearLayout> </layout>
Advantages of using data binding
- It allows you to effortlessly communicate across views and data sources.
- Reduces overhead from developers.
- More cleaner UI classes.
Drawbacks of using data binding
- Difficult to debug because you can’t set breakpoints in xml.
- Less readable code.