How To Implement Data Binding In Android Application

Posted By : Keshav Gupta | 19-Jun-2018

Step1: Enable databinding in app/build.gradle/android/ which enable databinding in application.

android {
    dataBinding{
        enabled=true
    }
}

Step2:Now we will create a xml layout file named activity_layout_databinding.xml.We will configure layout as per databinding.Following points will be there.

  • root element should start with a <layout>.Along with this tag <data> and <variable> tags are used in it.
  • <layout> tag will contain usual code of layout file.
  • <data> tag will be first tag after <layout> which will further contain <variable> tag which has two elements name and type.Name will be alias name and type will be of object model class
  • All the binding variable and method will go inside <data> tags.
  • To bind a value to a view @annotation will be used.In the layout file below user firstname,fullname and email are bound to TextView using @{user.firstName},@{user.fullName} and @{user.userEmail}respectively.
  • Above user is a model class referrence for all the object attributes.
  • layout code will be like.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="user"
            type="com.wecare.beans.User" />
        <variable
            name="handlers"
            type="com.wecare.controllers.activities.SampleBindingActivity.MyClickListener" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_firstname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="@dimen/margin_10"
            android:text="@{user.firstName}"
            android:textColor="@color/colorBlueText" />

        <TextView
            android:id="@+id/tv_fullname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_10"
            android:padding="@dimen/margin_10"
            android:text="@{user.fullName}"
            android:textColor="@color/colorBlueText" />

        <TextView
            android:id="@+id/tv_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_10"
            android:padding="@dimen/margin_10"
            android:text="@{user.userEmail}"
            android:onClick="@{handlers::onTextClicked}"
            android:textColor="@color/colorBlueText" />

        <Button android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Clicked"
            android:onClick="@{handlers::onButtonClick}"
            />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{(v) -> handlers.onButtonClickWithParam(v, user)}"
            android:text="CLICK WITH PARAM" />

        <Button android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="LongPress"
            android:onLongClick="@{handlers::onButtonLongPressed}"
            />

    </LinearLayout>
</layout>

Step3 :After above changes now perform build/clean and build/rebuild operations.This will generate corresponding databinding class.So in our case it will be ActivityLayoutDatabindingBinding.class.Note Binding suffix it refers the binding class for binded layout.

Step4: We will be creating a User model class having attribute firstName,fullName and userEmail and their corresponding getter,setter.Please ignore @bindable annotation ,BaseObservable and notifyPropertyChange() method.I will be explaining later.Code will be like

public class User extends BaseObservable {
    private String firstName,fullName,userEmail;

    @Bindable
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
        notifyPropertyChanged(BR.firstName);
    }

    @Bindable
    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
        notifyPropertyChanged(BR.fullName);
    }

    @Bindable
    public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
        notifyPropertyChanged(BR.userEmail);
    }
}

Step5:Now we will be creating a Activity class named as SampleBindingActivity.class.Now to bind the data in ui we will first inflate the binding layout using generated binding class and then bind the user object to layout file.Below file ActivityLayoutDatabindingBinding class will inflate the layout and then binding .setUser() will bind the object to layout file.You can find that no find view by id is used here.Code will be like:

public class SampleBindingActivity extends AppCompatActivity {
    ActivityLayoutDatabindingBinding dataBinding;
    User user;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_layout_databinding);
        user = new User();
        user.setFirstName("Keshav");
        user.setFullName("Keshav Gupta");
        user.setUserEmail("[email protected]");
        dataBinding.setUser(user);
 }

Now if we run the app we will find data displayed in TextViews.

We can also bind event methods to layout file.For that we will be creating class having click method,longclick event method and method taking param.And to use that we will be setting handlers using binding class object and in layout file we will be adding binding for methods using @{handlers::onButtonClick} likewise.Refer Step2.So a inner class will be added in SampleBindingActivity class. Now code will be like

public class SampleBindingActivity extends AppCompatActivity {
    ActivityLayoutDatabindingBinding dataBinding;
    MyClickListener handlers;
    User user;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_layout_databinding);
        user = new User();
        user.setFirstName("Keshav");
        user.setFullName("Keshav Gupta");
        user.setUserEmail("[email protected]");
        dataBinding.setUser(user);
        handlers = new MyClickListener();
        dataBinding.setHandlers(handlers);
    }

    public class MyClickListener {
        public void onTextClicked(View view) {
            user.setFirstName("Monu");
            user.setFullName("Monu Gupta");
            user.setUserEmail("[email protected]");
            dataBinding.setUser(user);
            AppToast.showToast(getApplicationContext(), "Text is clicked", Toast.LENGTH_SHORT);
        }

        public void onButtonClick(View view) {
            user.setFirstName("Krish");
            user.setFullName("Krish Gupta");
            user.setUserEmail("[email protected]");
            Toast.makeText(getApplicationContext(), "Button clicked!", Toast.LENGTH_SHORT).show();
        }

        public void onButtonClickWithParam(View view, User user) {
            Toast.makeText(getApplicationContext(), "Button clicked! Name: " + user.getUserEmail(), Toast.LENGTH_SHORT).show();
        }

        public boolean onButtonLongPressed(View view) {
            Toast.makeText(getApplicationContext(), "Button long pressed!", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}

Remember I suggest you to avoid @Bindable annotation and notifyPropertyChange() methods while building bean class.This is for if we want to  update the ui without calling setter methods.So we will be using Observable.UI will be updated when value of a property changes in an Object.So to make a Object class like to behave extend class from BaseObservable.

  • implement @Bindable annotation to getter behaviours for object attributes you wanted to track change
  • mention notifyPropertyChange(BR.attrib_name) method in setter method to reflect  the UI whenever data is changed.
  • BR class will be generated automatically if databinding is enabled.
  • Please refer Step4 for code.

Well to test this I have already updated data on buttonclick.You can check now.

This was some insights in Android Databinding.There is much more further. 

 

 

 

 

 

 

 

 

 

 

 

About Author

Author Image
Keshav Gupta

Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.

Request for Proposal

Name is required

Comment is required

Sending message..