What is databinding in Android? Example of Databinding.

  • What is Databinding
  • Databinding is used to optimise/minimize application code and logic to connect to the user   interface   elements. We can directly bind our java code to layout xml file.
  • Through Databinding we can  reduce code, make short and efficient code.
  • No need for doing findViewById every time for accessing xml control to java code
  • Databinding is supported from API leve 7+ (Android 2.1)
  • To use databinding need Gradle version 1.5+
  • Here i am going to examplaing how we can use data binding in our code step by step.
  
1)  Enable Databinding in app level build.gradle file any sync project


    dataBinding{
       enabled = true    }

2) Create modals package under java folder and also create modal name User.java


public class User extends BaseObservable {


    private String firstName;
    private String lastName;
    private String imageUrl;

    public User(String firstName, String lastName, String imageUrl) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.imageUrl = imageUrl;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getFirstName() {
        return firstName;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @BindingAdapter({"bind:imageUrl"})
    public static void loadImage(ImageView view, String imageUrl) {
        Picasso.with(view.getContext())
                .load(imageUrl)
                .placeholder(R.color.colorAccent)
                .into(view);
    }
}

Above class contains properties and getter-setter methods, we have also make function for loadImage() to load remote image from url

3) Create layout file named activity_main.xml under layout folder


<?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="user"
            type="modals.User" />

    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.chirag.databindingdemo.DemoActivity">

        <TextView
            android:id="@+id/tvLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:text="@{user.firstName+' '+user.lastName}"/>


        <ImageView
            android:id="@+id/imageView"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_below="@+id/tvLabel"
            android:layout_marginTop="15dp"
            android:layout_centerHorizontal="true"
            app:imageUrl="@{user.imageUrl}"
            />

    </RelativeLayout>
</layout>

In above code we have declare <layout> tag as a root tag. When using data binding, our whole layout should be under <layout> tag.

Then we have <data> tag where we can declare our modals which we can later use in layout.xml file for setting property values.

<data>
        <variable
            name="user"
            type="modals.User" />

    </data>

- Here i have declared <variable> tag, in this we can write name as variable name for
  accessing modal properties i have give name "user" in my case you can give any name.

- In type we have to provide our modal class path with package name.
- "@{}" is used for declaring any logical expression. We can use our modal variable to
  specifying property like "@{user.firstName}" in my case.

- In ImageView we have declare custom property for loading image through url
  app:imageUrl="@{user.imageUrl}", you can define this property based on varible name
  given in modal class for image url.


4) Finally create MainActivity.java



import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.example.chirag.databindingdemo.databinding.ActivityMainBinding;

import modals.User;


public class DemoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        User user = new User("Android", "DataBinding", "https://vignette1.wikia.nocookie.net/parody/images/9/97/Bob_minions_2015.png");
        binding.setUser(user);

    }

}

- Here ActivityMainBinding is auto generated variable, databinding library will    generate varible name according to you layout.xml file name with suffix of Binding  word. 

binding.setUser(user); here setUser() is auto generated function by databinding    library


:: Output



- Enjoy code ;)

Comments