As I shown in the previous post where we used BaseObservable 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 User2 which contains two variables firstName and lastName, both are ObservableFields.
Binding Class
package binding_demo.coderzheaven.com.bindingdemo; import android.databinding.ObservableField; public class User2 { public final ObservableField<String> firstName = new ObservableField<>(); public final ObservableField<String> lastName = new ObservableField<>(); }
For this we will make a small change in the layout to add new Binding Class.
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <data> <variable name="user2" type="binding_demo.coderzheaven.com.bindingdemo.User2" /> </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="@{user2.firstName}" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{user2.lastName}" /> <Button android:id="@+id/b1" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </layout>
Access and Set Data
// ObservableFields user2 = new User2(); user2.firstName.set("Google"); user2.lastName.set("Android"); binding.setUser2(user2);
user2.lastName.get();
Please try a Clean & Build if you are facing any issues
Source Code
You can find the full source code in my GitHub repository.