Android Data Binding Combat (i)

Source: Internet
Author: User

At this year's Google I/O conference, Google launched the design library and also launched the Android data binding, then what is the data binding? Its name is data binding, using it we can easily implement the MVVM (model-view-view model) mode, to achieve the separation of data and views between applications, the separation of views and business logic, and the separation of data and business logic, so as to achieve low coupling, reusability, ease of testing and other benefits, So let's first look at what is the MVVM pattern.

I drew a picture myself to help understand, not much to describe, after all, the focus is the use of data binding

We can clearly understand the benefits of this architectural pattern.
So the next step is to look at the use of data binding:

Building a development environment using data binding

At present, the data binding can only be in Android Studio 1.3 and above, and the Gradle version must be more than 1.3, so there is no upgrade upgrade equipment first.

    • Construction of the environment
      Create a new project, and first configure the dependencies in the Build.gradle file in the project root directory:
{        classpath ‘com.android.tools.build:gradle:1.3.+‘        classpath ‘com.android.databinding:dataBinder:1.0-rc1‘    }

Then configure it in the Build.gradle file in the App module directory:

‘com.android.application‘‘com.android.databinding‘

The first time you use the as download, you will be prompted to build SUCCESS when the configuration environment is successful.

use data Binding to write a demo of a simple MVVM pattern

Once the environment has been built, you need to know three points before using the data binding:

    1. In the XML layout that needs to be bound, we needto use < layout > as the outermost
    2. It is the binding of the data in the XML layout file, so it contains a< data > zone in the < layouts> Layout, where the data model bound to XML is set
    3. After the data model is obtained, bind the data to the corresponding control using the @{} expression.

So in this demo, we have a user model class->user, and the requirement is to use the data binding to display the user's username and password through TextView.
We first put the XML layout in the outermost layer with a <layout, and then add the< data > zone and set the binding model, and finally use the @{} expression to bind the data to the TextView control. So let's look at the layout of the XML:

<layout xmlns:android="Http://schemas.android.com/apk/res/android"  Xmlns:tools="Http://schemas.android.com/tools">        <data>        <variablename="user"type="Com.sunzxyong.databinding.User"/ >                            </Data>    <linearlayoutandroid:layout_width="Match_parent"android:layout_ Height="Match_parent"android:orientation="vertical"tools:context =". Mainactivity ">                                        <TextViewandroid:layout_width="Wrap_content"android:layout_height= "Wrap_content" Android:text="@{user.username}" />                                            <TextViewandroid:layout_width="Wrap_content"android:layout_height ="Wrap_content"android:text="@{user.userpassword}" />                                        </linearlayout></layout>

And look at the user class:

 Public classUser {PrivateString UserName;PrivateString UserPassword; PublicStringGetUserName() {returnUserName; } Public void Setusername(String userName) { This. userName = UserName; } PublicStringGetuserpassword() {returnUserPassword; } Public void SetUserPassword(String UserPassword) { This. UserPassword = UserPassword; } Public User(String userName, String userpassword) { This. userName = UserName; This. UserPassword = UserPassword; }}

One by one explain what it means, above we use:

<data>        <variable            name="user"            type="com.sunzxyong.databinding.User"/>    </data>

is to bind an object of the user class under the Com.sunzxyong.databinding package to the layout, and name= "user" is to define a user variable named user (the name can be arbitrarily taken), and then through @{user.username} The user name for this object is set to TextView (where User.username gets the data because it accesses the GetUserName () method in the user object to get the data).
Next look at the code, we use ViewModel to pass the data to the view layer in the OnCreate () method in activity:

protected   void  oncreate  (Bundle savedinstancestate) {super        . OnCreate (savedinstancestate); Activitymainbinding mbinding = Databindingutil.setcontentview (this ,        R.layout.activity_main); User user = new  User ( "Sunzxyong" , " 12345678 ");    Mbinding.setuser (user); }

Yes, you are not wrong, that is, through a few lines, no longer findviewbyid, the user's user name Sunzxyong and password 12345678 is bound to the corresponding textview on the display. Here is a detailed explanation of how it works:
Just now our <data> Zone in the layout file defines a user variable of type user, which defaults to the user object generating the SETUSER () and GetUser () methods. We can set the data by calling the Setuser () method after we get its ViewModel object, so what is the ViewModel class? By default, the system will automatically generate the ViewModel class according to the name of the XML layout, for example, just as our layout name is Activity_main, then it will end with an underscore for the separation point and a binding. So our ViewModel is activitymainbinding, we get the ViewModel of the corresponding XML file through Databindingutil.setcontentview (), Of course, the usual databindingutil.inflate () is the same, and finally we pass the data to the view layer through ViewModel.

Let's run it to see:

With the data binding, we show the information to the interface instead of using Findviewbyid to find the control and set the data.

Summary: Through it we have the data, interface, business logic, the three layer is very good decoupling, data layer model obtained data through the ViewModel object Setuser () method to set the data to the view layer for display, After the interface layer view obtains the user input data, it obtains the data of the view layer through the GetUser () method of the ViewModel object and passes it to the model layer update.

In this article we used the data binding to implement a simple demo, the next few will introduce more advanced usage of data binding!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. Reprint Annotated Source: http://blog.csdn.net/u010687392

Android Data Binding Combat (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.