Getting started with Android MVVM mode - use of DataBinding

Posted by clewis4343 on Fri, 21 Jan 2022 14:22:55 +0100

preface

The JetPack series has been updated: https://huanglinqing.blog.csdn.net/article/details/106215492

Update 2020.0405 - this article only explains the use of DataBinding, not MVVM architecture

This should be the second article on development mode. The first article explains the use of Android MVP mode: https://blog.csdn.net/huangliniqng/article/details/80570920

The advantages of mvp mode are not mentioned, but the disadvantages are obvious in the process of use. For example, there is a need to add, delete, modify and query the student table in the database, and we may have the following definitions for the view interface

interface view{

    void get();

    void delete();

    void add();

    void update();

}

The view layer we use can inherit the following interfaces, but if there are two activities, one needs to query, one needs to modify, and one needs all functions, if we inherit the view interface at this time, there will certainly be unused interfaces in the view layer. Of course, we can put the four interfaces in the four view layers, but the workload and maintenance are not convenient.

1, Android MVVM introduction

Personally, the emergence of MVVM is not to solve the shortcomings of the above MVP. Whether MVP, MVC or MVVM have their own shortcomings and advantages. Choosing an appropriate development mode in development can help the development work.

MVVM is not divided into four layers, but changes the P layer in MVP into ViewModel layer. Take the query data as an example. If we want to display the queried data on the control, we need to define the following methods of the view layer

void setData(String data);

setText is carried out in the interface callback of Activity. However, if a large amount of data is displayed, it needs to be set multiple times. The best way to use MVVM is MVP+DataBinding. MVVM can directly bind data to View layer controls and listen to events. Next, let's introduce the steps of using MVVM.

2, Usage steps of DataBinding

2.1 introduction of Data Binding function library

In build The following settings are used in gradle to support dataBinding:

dataBinding{
    enabled = true
}

2.2 create a User entity class

To simulate the data, we create a new User class as follows

public class User {

    private String UserName;
    private String UserSex;

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public String getUserSex() {
        return UserSex;
    }

    public void setUserSex(String userSex) {
        UserSex = userSex;
    }

    public User(String userName, String userSex) {
        UserName = userName;
        UserSex = userSex;
    }
}

2.3 write xml layout. There are two textview s, one displaying UserName and the other displaying UserSex. In ordinary xml layout, we use LinearLayout or other viewgroups, but in mvvm, the root layout is layout. The xml layout code is as follows:

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

    <data>
        <variable
            name="User"
            type="lonbon.com.mvvm.bean.User" />
    </data>

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

        <TextView
            android:id="@+id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{User.userName}" />

        <TextView
            android:id="@+id/userSex"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{User.userSex}" />

    </LinearLayout>
</layout>

In the layout, we should pay attention to this data note, in which the type field is the entity class corresponding to the data binding, and the name is an attribute flag we refer to, which is written here as User. If we want to assign a value to textview, we can directly assign the userSex Attribute Variable to textview with userSex id through @ {User. Attribute}.

2.4 reference in Activity

We think we have configured the databinding property to be true, so the Binding class will be automatically generated for us. The generation rule is to add Binding after the layout name. For example, the layout name here is activity_main, the generated Binding class is ActivityMainBinding, which we use in the Activity through the following code:

ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
User user = new User("Huang Linqing", "male");
activityMainBinding.setUser(user);

We obtain the databinding class through DataBindingUtil, bind it directly to the User data, and run the program, then the userName and userSex will be assigned to the corresponding values directly.

The results are shown in the figure:

If we assign a value to the control in the Item in the ListView, the code in the xml layout is the same, except that the binding class is obtained by using the

ListItemBinding bingding = ListItemBinding.inflate(layoutInflater,ViewGroup,false);

Or use

ListItemBinding bingding = DataBindingUtil.inflate(layoutInflater,R.layout.activity_main,ViewGroup,false);

3, Listening events used by DataBing

In fact, I personally feel that the effect of using DatabBing to listen to events is not good, because ButterKnife is almost used to directly generate listening events. However, we still need to mention that we add a button to the previous layout and assign a listening event to the button. First, we define a class to listen to events, We can handle all listening events in this class, which is similar to js, which is also a benefit.

3.1 define a Click class and declare a test listening method

The code is as follows:

public class Click {

    private String tag = "click";
    public void test(View v) {
        Log.d(tag, "Click event triggered");
    }
}

3.2 binding in xml

Add another variable tag to the data tag

<variable
    name="Click"
    type="lonbon.com.mvvm.click.Click"/>

Set the onclick property in the button

<Button
    android:text="text"
    android:onClick="@{Click.Text}"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Finally, remember to set in activity:

activityMainBinding.setClick(new Click());

It should be noted here that setClick method is not called. If the newly created listening method class is Text, setText should be called to bind listening events. Let's click the button and print the results as follows:

This is the main use of DataBinding. There are still some functions that need to be further studied and shared later