Full introduction to the MVVM framework of Android-Data Binding

Source: Internet
Author: User
Tags xml attribute

Full introduction to the MVVM framework of Android-Data Binding

MasteringAndroidDataBinding

This tutorial is based on some practical experience gained from the learning process of Data Binding Guide. It also modifies some errors of the official tutorial. Each knowledge point has the corresponding source code, we strive to combine practice with theory.

Data Binding solves a pain point in Android UI programming. The official native support for MVVM models makes it easy to use these new features without changing the existing code framework. In fact, some third-party frameworks (RoboAndroid) have been able to support MVVM models before, but they have never been popular due to the framework's too invasive nature.

Update Android Studio to version 1.3.

Open Preferences and findAppearances & BehaviorUnderUpdatesOptionAutomatically Check updatesModifyCanary Channel.

Note:

Data Binding is a support package, so it has nothing to do with Android M. You do not need to download the Android MNC Preview SDK.

Create a Project

Modify build. gradle of the Project and add a dependency for build script. The Gradle version is 1.2.3.

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

Add a plug-in to the module that uses Data Binding and modify the corresponding build. gradle.

apply plugin: 'com.android.databinding'

Note:

If the ModuleBuildToolsVersionHigher22.0.1For example23 rc1, Thatcom.android.databinding:dataBinderTo change1.3.0-beta1Otherwise, the following error occurs:

Basic

After the project is created, we use a simple example to describe the basic usage of Data Binding.

Layout File

After using Data Binding, the xml layout file does not simply display the UI elements, but also needs to define the variables used by the UI elements. Therefore, its root node is no longerViewGroupBut changedlayoutAnd a node is added.data.


      
           
       
   
    
....
   
  

To implement the MVVM ViewModel, You need to bind the data to the UI,dataThe node provides a bridge for this purpose.dataDeclare one invariableThis variable will provide data for the UI element (for example, the android: text of TextView), and then integrate the "background" data with thisvariable.

How can we use Data Binding to display basic user information in a table?

Data Object

Add a POJO class-User, Which is very simple. Four attributes and Their getter and setter.

public class User {    private final String firstName;    private final String lastName;    private String displayName;    private int age;    public User(String firstName, String lastName) {        this.firstName = firstName;        this.lastName = lastName;    }    public User(String firstName, String lastName, int age) {        this(firstName, lastName);        this.age = age;    }    public int getAge() {        return age;    }    public String getFirstName() {        return firstName;    }    public String getLastName() {        return lastName;    }    public String getDisplayName() {        return firstName + " " + lastName;    }    public boolean isAdult() {        return age >= 18;    }}

Later, we will create a newUserType, and then bind it with the variables declared in the layout file.

Define Variable

Return to the layout filedataDeclare a variable in the nodeuser.

    
   

WheretypeAttribute is defined in the Java file.UserClass.

Of course,dataNodes are also supportedimportSo the above Code can be written in another form.

    
       
    
   

Then the plug-in we just added in build. gradle-com.android.databindingBased on the name of the xml fileGenerateAn inherited fromViewDataBinding.

For example, the xml file name isactivity_basic.xmlThe generated class isActivityBasicBinding.

Note:

java.lang.*Classes in the package will be automatically imported and can be directly used. For example, to defineStringType variables:


  
Bind Variable

ModifyBasicActivityOfonCreateMethod, useDatabindingUtil.setContentView()To replacesetContentView()And then createuserObject throughbinding.setUser(user)Andvariable.

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

Note:

ActivityBasicBindingClass is automatically generated, and all the set methods are based onvariableName generated. For example, we define two variables.

    
       
    
   

The corresponding two set methods are generated.

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

After the data is bound to Variable, the xml UI element can be used directly.


  

Now, a simple data binding is complete. Refer to the complete code.

Advanced usage

First, add a static method for the class.

public class MyStringUtils {    public static String capitalize(final String word) {        if (word.length() > 1) {            return String.valueOf(word.charAt(0)).toUpperCase() + word.substring(1);        }        return word;    }}

ThendataNode import:


  

The usage is the same as the Java Syntax:


  
Type alias

If wedataWhen a node imports two classes with the same name, what should I do?


  
   
    
   
  

In this way, twoUserClass, thatuserWhich one does the variable use? Don't worry,importThere is anotheraliasAttribute.


  
   
    
   
  
Null Coalescing Operator
android:text="@{user.displayName ?? user.lastName}"

It is equivalent

android:text="@{user.displayName != null ? user.displayName : user.lastName}"
Attribute Value

Pass${}You can directly assign the attribute values defined in Java to the xml Attribute.


  
Use resource data

This example shows an error in the official tutorial. You can refer to a bug in Android Data Binder. The complete code is here.


  

Related Article

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.