Comprehensive introduction to Android's MVVM framework-data binding

Source: Internet
Author: User

Original Address masteringandroiddatabinding

This tutorial is to follow the Data Binding Guide to learn some of the practical experience, while revising some of the official tutorial errors, each knowledge point has a corresponding source code, to achieve the combination of practice and theory.

The Data Binding solves a pain point in Android UI programming, and the official natively supported MVVM model allows us to use these new features very easily without changing the existing code framework. In fact, prior to this, there have been some third-party frameworks (Roboandroid) that can support the MVVM model, and the lack of resistance due to the intrusive nature of the framework has led to a lack of popularity.

Prepare for Android Studio update to version 1.3

Open Preferences and find the updates option under appearances & Behavior to modify the automatically Check updates for Into Canary Channel.

Attention

The Data Binding is a support package, so it doesn't have anything to do with Android M, so you don't have to download the Android MNC Preview SDK.

Create a new Project

Modify Project's Build.gradle, add a dependency to the build script, and the Gradle version is 1.2.3.

‘com.android.tools.build:gradle:1.2.3‘‘com.android.databinding:dataBinder:1.0-rc0‘

Add a plugin to the module that uses the Data Binding and modify the corresponding build.gradle.

‘com.android.databinding‘

Attention

If the Module uses a buildtoolsversion higher than 22.0.1, such as the RC1, then com.android.databinding:dataBinder the version should be changed to 1.3.0-beta1, Otherwise, the following error will occur:

Basis

Once the project has been created, we use a simple example to illustrate the basic usage of Data Binding.

Layout file

With Data Binding, the layout file of the XML no longer simply presents the UI elements, but also defines the variables used by the UI elements. So, its root node is no longer one ViewGroup , but it becomes layout , and a new node is added data .

<layout xmlns:android="http://schemas.android.com/apk/res/android">    <data>    </data>    <!--原先的根节点(Root Element)-->    <LinearLayout>    ....    </LinearLayout></layout>

To implement the ViewModel of MVVM, you need to bind the data to the UI, and the data node provides a bridge where we first data declare a variable variable that provides the data for the UI element (for example, TextView android:text). The "background" data is then bound to this in the Java code variable .

If you want to use a table to show the user's basic information, how should the Data Binding be implemented?

Data Objects

Add a POJO class-- User very simple, four attributes and their getter and setter.

 Public  class User {    Private FinalString FirstName;Private FinalString LastName;PrivateString DisplayName;Private intAge Public User(String firstName, String lastName) { This. firstName = FirstName; This. lastName = LastName; } Public User(String firstName, String lastName,intAge) { This(FirstName, LastName); This. Age = Age; } Public int Getage() {returnAge } PublicStringGetfirstname() {returnFirstName; } PublicStringGetlastname() {returnLastName; } PublicStringGetDisplayName() {returnFirstName +" "+ LastName; } Public Boolean Isadult() {returnAge >= -; }}

Later, we will create a new User variable of type and bind it to the variable declared in the layout file.

Define Variable

Then go back to the layout file and data declare a variable in the node user .

<data>    <variable name="user" type="com.liangfeizc.databindingsamples.basic.User" /></data>

typethe properties are the classes we define in the Java file User .

Of course, data nodes are also supported import , so the above code can be written in a different form.

<data>    <import type="com.liangfeizc.databindingsamples.basic.User" />    <variable name="user" type="User" /></data>

And then the plug-in we just added in Build.gradle- com.android.databinding Generate A class that inherits from the name of the XML file ViewDataBinding .

For example, here the XML file name activity_basic.xml , then the generated class is ActivityBasicBinding .

Attention

java.lang.*The classes in the package are automatically imported and can be used directly, for example to define a String variable of type:

<variable name="firstName" type="String" />
Binding Variable

Modify BasicActivity The onCreate method, DatabindingUtil.setContentView() replace setContentView() it with, and then create an user object to binding.setUser(user) bind with variable .

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    ActivityBasicBinding binding = DataBindingUtil.setContentView(            this, R.layout.activity_basic);    new User("fei""Liang");    binding.setUser(user);}

Attention

ActivityBasicBindingClasses are generated automatically, and all set methods are generated by variable name. For example, we have defined two variables.

<data>    <variable name="firstName" type="String" />    <variable name="firstName" type=""</data>

Then a corresponding two set method is generated.

setFirstName(String firstName);setLastName(String lastName);
Using Variable

After the data is bound to Variable, the UI elements of the XML can be used directly.

<TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@{user.lastName}" />

At this point, a simple data binding is complete, and you can refer to the complete code

Advanced usage Use class methods

First, add a static method to the class

publicclass MyStringUtils {    publicstaticcapitalize(final String word) {        if1) {            return String.valueOf(word.charAt(0)).toUpperCase() + word.substring(1);        }        return word;    }}

Then, in the XML data node, import:

<import type="com.liangfeizc.databindingsamples.utils.MyStringUtils" />

Use the same method as in Java syntax:

<TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@{StringUtils.capitalize(user.firstName)}" />
Type aliases

What if we data have imported two classes with the same name on the node?

<import type="com.example.home.data.User" /><import type="com.examle.detail.data.User" /><variable name="user" type="User" />

So there are two User classes, user which one is the variable? Don't worry, import there's a alias property.

<import type="com.example.home.data.User" /><import type="com.examle.detail.data.User" alias="DetailUser" /><variable name="user" type="DetailUser" />
Null coalescing operator
android:text="@{user.displayName ?? user.lastName}"

is equivalent to

android:text="@{user.displayName != null ? user.displayName : user.lastName}"
Property value

${}the attribute values defined in Java can be assigned directly to an XML property.

<TextView   android:text="@{user.lastName}"   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:visibility="@{user.isAdult ? View.VISIBLE : View.GONE}"/>
Working with Resource data

This example, the official tutorial has errors, you can refer to the Android Data Binder a bug, the complete code here.

<TextView    android:padding="@{large? (int)@dimen/largePadding : (int)@dimen/smallPadding}"    android:background="@android:color/black"    android:textColor="@android:color/white"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@string/hello_world" />

Comprehensive introduction to Android's MVVM framework-data binding

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.