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:dataBinder
To 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 longerViewGroup
But changedlayout
And a node is added.data
.
....
To implement the MVVM ViewModel, You need to bind the data to the UI,data
The node provides a bridge for this purpose.data
Declare one invariable
This 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 newUser
Type, and then bind it with the variables declared in the layout file.
Define Variable
Return to the layout filedata
Declare a variable in the nodeuser
.
Wheretype
Attribute is defined in the Java file.User
Class.
Of course,data
Nodes are also supportedimport
So the above Code can be written in another form.
Then the plug-in we just added in build. gradle-com.android.databinding
Based on the name of the xml fileGenerateAn inherited fromViewDataBinding
.
For example, the xml file name isactivity_basic.xml
The generated class isActivityBasicBinding
.
Note:
java.lang.*
Classes in the package will be automatically imported and can be directly used. For example, to defineString
Type variables:
Bind Variable
ModifyBasicActivity
OfonCreate
Method, useDatabindingUtil.setContentView()
To replacesetContentView()
And then createuser
Object 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:
ActivityBasicBinding
Class is automatically generated, and all the set methods are based onvariable
Name 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; }}
Thendata
Node import:
The usage is the same as the Java Syntax:
Type alias
If wedata
When a node imports two classes with the same name, what should I do?
In this way, twoUser
Class, thatuser
Which one does the variable use? Don't worry,import
There is anotheralias
Attribute.
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.