1. Introduction

2. Summarize MVC and MVP

3. What is MVVM

4. What is DataBinding

5. Simple examples

6. Summary

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

1. Introduction

A new framework was introduced at Google I/O 2015, called DataBinding. What is DataBinding? Data binding.

2. Summarize MVC and MVP

What is MVVM before I say DataBinding? It has been more than ten years since the birth of Android, and the most mainstream MVC, MVP and MVVM three code architecture development modes have emerged one after another. The following is a brief analysis of the characteristics and advantages and disadvantages of the three development modes.

MVC

The full name of MVC is Model View Controller is the abbreviation of Model, View and Controller.

M: A Model is an encapsulation of application state and business functions. It can be understood as a domain Model that contains both data and behavior. Typically, Model objects are responsible for accessing data in a database.

V:View is the part of the application that deals with data display, which is to realize the presentation of visual interface and capture the user’s interactive operations. In Android, it can be an Activity, a Fragment or a Dialog. The View can call the Model directly to query state information, and the Model can actively notify the View when its state changes. Views are usually created from model data.

C:Controller is the part of the application that handles user interaction. Is the connector between M and V that controls the flow of the application. The View captures the user interaction and sends it directly to the Controller, which does the corresponding UI logic. If there are calls involving business functions, the Controller directly calls the Model and modifies the Model state. The Controller can also actively control the original View or create a new View in response to user interaction. Typically the controller is responsible for reading data from the view, controlling user input, and sending data to the model.

Here is a graph to show the relationship between the three:

If MVC and View can access Model directly, then the View will contain information about Model and inevitably also some business logic. In the MVC Model, more attention is paid to Model changes, and there are multiple different displays of the Model at the same time, namely views. So, in an MVC Model, the Model doesn’t depend on the View, but the View does depend on the Model. Now think about it, for Android, activity basically assumes two roles of view layer and Controller layer, and is seriously coupled with model layer, which is very troublesome to maintain in the interface with complex logic. Then the MVP comes out and cuts off the relationship between View and Model.

MVP

MVP’s full name is Model-view-Presenter which is short for Model, View, Presenter.

M and V have been explained above, now p: A presenter gets data from the Model and feeds it to the View layer. The simple thing is that when the View needs to update its data, the presenter goes to the Model and asks for data from the Model and notifies the presenter. The Presenter notifies the View to update the data. In short: what data to return to the View.

Here is a graph to show the relationship between the three:

Here are some of the MVP’s strengths:

1. Strictly forbid interaction between a View and a Model. It must be done by Presenter. The independence of the Model is truly demonstrated, not only by the rendering of visual elements (views), but also by the UI processing logic. Applications that use MVP are user-driven, not Model-driven, so the Model does not actively notify the View.

2. The “V” in MVP mode represents an interface, which abstracts the UI interface. An interface means that any interface that implements it can reuse existing Presenter and Model code. A mode that truly isolates the details and complexity of a View and reduces presenters’ dependency on the View. The advantage is that the processing logic in Presenter’s UI becomes easier to test.

3. What is MVVM

If MVP is a further improvement on MVC, MVVM is a complete change in thinking. MVVM stands for model-view-viewModel.

MVVM types MVC and MVP, but more powerful than these two. Mv-vm vs. MVP essentially replaces the Presenter layer with the ViewModel layer. MVVM is based on the idea of “two-way binding of data Model data”, so there is no connection between View and Model, but interaction through ViewModel, and the interaction between Model and ViewModel is two-way, so the change of View data will modify the data source at the same time. Changes to the data source are immediately reflected in the View.

The ViewModel layer needs to do is completely logic-related code, completely does not involve UI, when the data changes, directly drive UI changes, eliminating redundant interface in the middle, in the ViewModel layer code, requires developers to do each method as far as possible a single function, do not have any connection with the outside, Improved code robustness for later unit testing.

Similarly, the following chart shows the relationship among the three:

In addition to the familiar Model, View, and ViewModel parts, MVVM implementations also introduce an implicit Binder layer that binds declarative data to commands in MVVM mode.

From MVC architecture mode to MVVM, from separation layer to display model layer, after decades of development, MVC architecture mode has appeared various varieties, and has its own implementation on different platforms, developers can according to the actual situation and their own advantages and disadvantages to adopt what mode to develop.

4. What is DataBinding

MVVM is based on the idea of “binding data to the data model”. Views and ViewModels have an implicit BInder layer. How do they implement one-way or bidirectional binding? Is through the DataBinding framework to achieve the implementation of UI and DataBinding framework, so that the UI and data monitoring each other, the task assignment of developers is very clear, responsible for ViewModel developers do not have to consider how to achieve the UI, improve the efficiency of code development and the accuracy of tracking problems in the late.

5. Simple examples

Here’s a quick example to get started with DataBinding

Environmental requirements

  • DataBinding is a support library with minimum requirements on Android2.1
  • Android STdio version 1.3 and above
  • Gradle plugin 1.5 or above

Gradle configuration

Add DataBinding support to build.gradle at the module level: Note: If you want to use it in the library, then use that library to add support to build.gradle as well.

android{
   dataBinding{
          enabled = true}}Copy the code

Create an object

Let’s create an object named User

Public class User {// name private String name; Private Boolean isMale; // private int age; public StringgetName() {
        return name;
    }

    public User(String name, boolean isMale, int age) {
        this.name = name;
        this.isMale = isMale;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isMale() {
        return isMale;
    }

    public void setMale(boolean male) {
        isMale = male;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) { this.age = age; }}Copy the code

Fill in the layout file

<? xml version="1.0" encoding="utf-8"? > <layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{user.name}"/ > <! <TextView Android :layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{String.valueOf(user.isMale)}"/ > <! --> <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{String.valueOf(user.age)}" />

    </LinearLayout>
</layout>
Copy the code

The root node of the layout file is layout, and the child nodes of layout are divided into two parts. The first part is data node, which is used to create variables. The data node acts as a bridge between View and Model. The second part is the root node of previous development. A variable is defined under the data node. Variable represents the declared variable, where name represents the name of the variable and type represents the type of the variable, so that the value can be easily passed to the layout file. Note that the control TextView does not define an ID, but uses @{}(@{bean.xxx}) to bind to the data user in the text.

The Activity file

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);

        ActivityMainBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        User user = new User("Dog".true,24);
        binding.setUser(user);
    }
}
Copy the code

Found no findViewById or ButterKnife initializer for the control, and no control setting data. Binding layout file by DataBindingUtil. Replace the setContentView the setContentView. Bind to variable via binding.setUser(Bean). Note: in/build/generated/source/apt/debug/comapt/debug/com. Android. Can see ActivityMainBinding databinding/databinding. This class rules are generated activity_main – > ActivityMainBinding, fragment_main – > FragmentMainBinding. The first word is capitalized, the second word is capitalized, and Binding is spelled at the end. The actual results are as follows:

DataBinding {enabled = true}

Android Stdio relies on Gradle to manage build projects. We know that a project needs to execute many tasks (tasks). Many tasks are predefined by the system, such as: Build task, clean task. By default, Databinding {enable = true} is not enabled, so it is not in the task list. The relevant task is executed to check and generate dataBinding related code.

2. How is the ActivityMainBinding class generated?

This class is automatically generated by the system. By default, the system will use the Databinding code generated for us by Android Stdio, but you will find that you cannot see the source code. You can view the source code in the build path described above or manually compile the code.

6. Summary

The main advantage of dataBinding is that the code in the Activity and Fragment layers is reduced. Instead of using findViewById, XML files can now be used to perform operations from the previous display layout. This article is just a first look at DataBinding, and its use will be explained later.