Monday 24 September 2018

Android Architecture Components : Data Binding Part 1

Hi ,

Today I am going to share the demo for data binding . According to android official docs: The Data Binding Library is a support library that allows you to bind UI components in your layout to data sources in your app using a declarative format rather than programmatically.

So as it is mentioned , this library is basically used to bind view of layout to view of activity, without using findViewById() .

Let's start with few coding, here I am showing a simple demo with 3 textviews and 1 profile picture form layout :

-> Firstly we need to download lib in Android SDK Manager : Support Repository 

-> Add Data Binding element into build.gradle :


android {
    dataBinding {
        enabled = true    }

-> Now let's design the layout , here you have to notice one thing , that parent tag of all layout should be :  <layout> </layout> only. This is used to create the by default binding class for each layout.If you forgot to add this tag as the parent tag , so we would not be able to get the binding class of this layout , in our activity class :

<?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>
        <import type="com.demo.databinding.utils.Utils" />
        <import type="android.view.View"/>
        <variable
            name="user"
            type="com.demo.databinding.model.User"></variable>

        <variable 
            name="handlers"
            type="com.demo.databinding.MainActivity.MyHandlers"></variable>
    </data>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp">


        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{Utils.capitalize(user.name)}"
            android:onClick="@{(view)-> handlers.onTextClicked(view)}"
            android:layout_margin="10dp"
            android:textSize="18sp"
            android:clickable="true"
            android:textColor="@color/colorAccent"/>

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{user.email}"
            android:onClick="@{(view)-> handlers.showEmail(view,user.email)}"
            android:layout_margin="10dp"
            android:textSize="18sp"
            android:textColor="@color/colorAccent"/>

        <TextView
            android:id="@+id/textView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{user.phoneNumber}"
            android:onClick="@{() -> handlers.onClickNumber()}"
            android:layout_margin="10dp"
            android:textSize="18sp"
            android:textColor="@color/colorAccent"/>

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Submit"
            android:layout_margin="10dp"
            android:textSize="18sp"
            android:onClick="@{()-> handlers.onSubmitButtonClicked(textView2, textView,textView3)}"
            android:textColor="@color/colorAccent"/>


    </LinearLayout>
    </ScrollView>
</layout>

The above layout (activity_main.xml), is having few textviews and button with one imageview,here we have used some tags, take a look:

-> <layout> - This tag is used as a parent tag of a layout, for data-binding it is compulsory.
-> <data> -  This tag is used to import any class for src to layout .
-> @{} - > It is used to define the particular callback on call any event.

Here in textviews we are setting different types of Strings/Numbers , which are managed by JAVA class , which we will show you further :

  1. android:text="@{Utils.capitalize(user.name)}"
  2. android:text="@{user.email}"
  3. android:text="@{user.phoneNumber}"
In above it is clear that User is an entity and name, email and phoneNumber has been set here like this.


Also in these 3 textviews we have different types of call onClick event , that are:

  1. onClick="@{(view)-> handlers.onTextClicked(view)}"
  2. onClick="@{(view)-> handlers.showEmail(view,user.email)}"
  3. onClick="@{() -> handlers.onClickNumber()}"
In Pt 1: We are passing the same textview object on click that textView.

In Pt.2: We are passing that textView and  email , which are setted by JAVA class (will explain you later)

In Pt. 3: We are calling this method without any parameters.

Now Let's take a look on User.class(entity class) :


public class User extends BaseObservable {
    String name;
    String email;
    String phoneNumber;

    @Bindable
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }

    @Bindable
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
        notifyPropertyChanged(BR.email);
    }

    @Bindable
    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
        notifyPropertyChanged(BR.phoneNumber);
    }
   
}

-> We have added a method in Utils class as well:

 public static String capitalize(String text) {
        return text.toUpperCase();
    }

-> Now let's move to MainActivity.class:

public class MainActivity extends AppCompatActivity {

    User user;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding dataBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);

        user = new User();
        user.setName("XYZ");
        user.setEmail("xyz@gmail.com");
        user.setPhoneNumber("9876543210");
       

        dataBinding.setUser(user);
        MyHandlers handlers = new MyHandlers(MainActivity.this);
        dataBinding.setHandlers(handlers);
    }

    public class MyHandlers{
        public MyHandlers(MainActivity activity) {
        }

        public void onTextClicked(View view){
            Toast.makeText(getApplicationContext(),"Text is Clicked!",Toast.LENGTH_LONG).show();
        }

        public void showEmail(View view, String email){
            Toast.makeText(getApplicationContext(),email+" is entered !!",Toast.LENGTH_LONG).show();
        }

        public void onClickNumber(){
            Toast.makeText(getApplicationContext(),"Phone number is clicked!!",Toast.LENGTH_LONG).show();
        }

        public void onSubmitButtonClicked(TextView name, TextView email, TextView phoneNumber){
            User user  =  new User();
            user.setName("PQR");
            user.setEmail("pqr@gmail.com");
            user.setPhoneNumber("1234567890");
            name.setText("PQR");
            email.setText("pqr@gmail.com");
            phoneNumber.setText("1234567890");
            Toast.makeText(getApplicationContext(),"Submit is clicked!!",Toast.LENGTH_LONG).show();

        }

        
    }

}


-> Above in MainActivity , we have set Content View , we have to call setContentView from DataBindingUtil class.

After that we will set all the variables of Entity class, in our case it is User.java.
then set it to ActivityMainBinding  class(it is a generated class mainly used for Binding data) 
Set the Handlers  object to this class also. That's it. Run the code and enjoy the data binding experience :) .For ImageView setting I will explain in next post ,till then Happy Coding :) 






No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...