As I shown in the previous post where we used BaseObservable and ObservableField to update UI when binding object is changed, this post will show you another simple way to achieve this.
Do Check my previous posts for better understanding of DataBinding and methods used in DataBinding.
Here is another way to do it. In this method we will use ObservableField to update the UI.
We will create a Bindable class named User3 which has one ObservableArrayMap member variable.
package binding_demo.coderzheaven.com.bindingdemo; import android.databinding.ObservableArrayMap; public class User3 { public ObservableArrayMap<Integer, String> name = new ObservableArrayMap<>(); }
The layout
Lets see how this class is being binded in the layout.
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <data> <variable name="user3" type="binding_demo.coderzheaven.com.bindingdemo.User3" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{user3.name.get(0)}" /> <Button android:id="@+id/b1" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </layout>
In the above layout, we have one binding variable named user3 and @{user3.name.get(0)} will get the date from the map which has a 0 as key. Below we will see how we will add data to this Map in java code.
Set Data
ActivityMainBinding binding = DataBindingUtil. setContentView(this, R.layout.activity_main); // Observable Collections user3 = new User3(); user3.name.put(0, "Coderz"); user3.name.put(1, "Heaven"); binding.setUser3(user3);
So In this example the retrieved data will be “Coderz“.
Update the Observable Collection
OnClick of the Button in the layout we will update the values in the UI by changing the object.
binding.b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Updating Observable Collections user3.name.put(0, "Heaven"); } });
Please try a Clean & Build if you are facing any issues
Source Code
You can find the full source code in my GitHub repository.