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.

  1. http://www.coderzheaven.com/2017/01/15/simple-databinding-in-android-example/
  2. http://www.coderzheaven.com/2017/01/20/data-binding-in-android-using-observables/

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>

Make easy money with infolinks

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.

Get the Source Code

Make easy money with infolinks

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.