神刀安全网

Simple Guidance For Data Binding – Part 1

Google has been pushing updates to existing tools and making the life of android developers easier. They also have been releasing new libraries and APIs which helps developers to create an application in an easy way and having followed proper architecture and able to achieve good performance. “Data binding” is one of them.

What is Data Binding

It is a mechanism to make a bridge between Presentation layer and Model layer, where Presentation layer contains UI widgets like TextView, EditText, List etc. and Model layer contains entities which hold information.

Why Data Binding?

When “Data binding” was not there, we are using traditional way to display model information in UI using “getter” and “setter” methods. Like, we have a “Model” class which represents entity information and we have references to UI widgets and getter methods from which we fetch data and display it over UI.

public class User  {      public String displayName;     public int age;      public User(String displayName, int age){         this.displayName = displayName;         this.age = age;     }      public int getAge() {         return age;     }      public void setAge(int age) {         this.age = age;     }      public String getDisplayName() {         return displayName;     }      public void setDisplayName(String displayName) {         this.displayName = displayName;     } }

And, below is code to display data in Presentation layer.

public class DataBindingActivity extends AppCompatActivity {      TextView txtDisplayName, txtAge;          @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main_activity);                  txtDisplayName = (TextView) findViewById(R.id.txtDisplayName);         txtAge = (TextView) findViewById(R.id.txtAge);          User user = new User("Chintan Rathod", 27);         txtDisplayName.setText(user.getDisplayName());         txtAge.setText(String.valueOf(user.getAge()));     } }

In above example, there is unnecessary code. Those “setText” methods are boilerplate code and a bit time consuming. We already have “IDs” of each widget then why to write code to map “Model” to it? Right!!

So to overcome this problem, Data binding is here and it provides easy a way to reduce your work by mapping model object in your layout.

How to use Data Binding

To implement Data Binding in your application, you need to follow below steps.

Step 1

Create a Project and open main Gradle file of the project.

Simple Guidance For Data Binding – Part 1

Main Gradle

Add below two lines in your dependencies tag

dependencies {     classpath 'com.android.tools.build:gradle:1.3.0'     classpath 'com.android.databinding:dataBinder:1.+' }

This will add a dependency to your project.

Step 2

Now open your module’s Gradle file. We require to add a plug-in to our project.

apply plugin: 'com.android.databinding'

Your whole Gradle file will look like this

apply plugin: 'com.android.application' apply plugin: 'com.android.databinding'  android {     compileSdkVersion 23     buildToolsVersion "23.0.2"      defaultConfig {         applicationId "chintan.rathod.databindingdemo"         minSdkVersion 15         targetSdkVersion 23         versionCode 1         versionName "1.0"     }     buildTypes {         release {             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     }  }  dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     testCompile 'junit:junit:4.12'     compile 'com.android.support:appcompat-v7:23.1.0' }

Step 3

An environment is ready with all dependencies integration. Let’s take an example of a person having his name and age. We will create a Model class with this properties first.

public class User  {      public String displayName;     public int age;      public User(String displayName, int age){         this.displayName = displayName;         this.age = age;     } }

You can see here, we have not created any “getter/setter” methods.

Step 4

Open your layout file and add layout tag as root of it. It is necessary to have layout tag and data tag. It holds information about which model(s) is/are using in layout.

<layout xmlns:android="http://schemas.android.com/apk/res/android">     <data>         <variable name="user" type="chintan.rathod.databindingdemo.Model.User"/>     </data>     ... </laoyout>

Here, data has variable tag describes which properties will be used in current layout. name defines name space and type defines package path of Model.

We tell layout that I want to use User model class in this layout. Now tell each widget which properties they are going to use. To access any member of User class, below is syntax

Syntax

android:text="@{user.memberName}"

Example

android:text="@{user.displayName}"

Here is full layout file code.

<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android">     <data>         <variable name="user" type="chintan.rathod.databindingdemo.Model.User"/>     </data>     <LinearLayout         android:orientation="vertical"         android:layout_width="match_parent"         android:layout_height="match_parent">          <LinearLayout             android:orientation="horizontal"             android:layout_width="match_parent"             android:layout_height="wrap_content">              <TextView                 android:layout_width="100dp"                 android:layout_height="wrap_content"                 android:text="Name:"                 android:textSize="22sp"/>              <TextView                 android:id="@+id/txtDisplayName"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:text="@{user.displayName}"                 android:textSize="22sp"/>          </LinearLayout>          <LinearLayout             android:orientation="horizontal"             android:layout_width="match_parent"             android:layout_height="wrap_content">              <TextView                 android:layout_width="100dp"                 android:layout_height="wrap_content"                 android:text="Age:"                 android:textSize="22sp"/>              <TextView                 android:id="@+id/txtAge"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:text="@{String.valueOf(user.age)}"                 android:textSize="22sp"/>         </LinearLayout>     </LinearLayout>  </layout>

If you noticed, I used android:text="@{String.valueOf(user.age)}" in layout. Why? Because age is an Integer argument and we can not directly set it to TextView .

Step 5

We are almost done with mapping. Now, we require to bind views to model in our Activity

When you use data tag in your layout, Android will auto generate a class with layout filename and a suffix “Binding”. For example, your layout file name is main_activity.xml then your autogenerated class name will be MainActivityBinding . This class holds all binding i.e. user in our case.

Open your activity class and write below code.

MainActivityBinding binding =                 DataBindingUtil.setContentView(this, R.layout.main_activity); User user = new User("Chintan Rathod", 27); binding.setUser(user);

Full Activity code.

import android.databinding.DataBindingUtil; import android.support.v7.app.AppCompatActivity; import android.os.Bundle;  import chintan.rathod.databindingdemo.Model.User; import chintan.rathod.databindingdemo.databinding.MainActivityBinding;  public class DataBindingActivity extends AppCompatActivity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main_activity);          MainActivityBinding binding =                 DataBindingUtil.setContentView(this, R.layout.main_activity);         User user = new User("Chintan Rathod", 27);         binding.setUser(user);     } }

Step 6

You’re done! Run the application.

Simple Guidance For Data Binding – Part 1

Data Binding Output

Download

Source code for this article is availablehere

Views: 5

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Simple Guidance For Data Binding – Part 1

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮