Android Advanced MVVM+DataBinding Framework Mode (Updating)

MVVM framework

Introduction to MVVM Architecture
C# has a MVVM development model very early, and MVVM in Android mobile phones was not launched until Google's I\O conference last year, not too late. Needless to say, the advantages of the development mode of MVVM can realize the decoupling of view and logic code. Moreover, according to Google, using the development mode of MVVM can also improve the parsing speed of layout files. I personally think this is very important. important. We often need to write a lot of findViewById in Android development, which is annoying. Many people don't want to write emperors, so they use some annotation frameworks. However, no matter how good the performance of the annotation framework is, the efficiency is always lower than that of findViewById. Therefore, in Android MVVM or databinding can help us solve this problem completely

The MVVM framework implements the binding of data and views (DataBinding). When the data changes, the view will be automatically updated; on the contrary, when the view changes, the data will automatically be the new
insert image description here
MVVM mode. Like the MVP mode, it also divides the application into three layers. , and the responsibilities of each corresponding layer are similar:

  • Model layer, which is mainly responsible for the provision of data. The Model layer provides the data structure of business logic (for example, entity classes), provides data acquisition (for example, acquires data from a local database or a remote network), and provides data storage
  • View layer, which is mainly responsible for the display of the interface. The View layer does not involve any business logic processing. It holds a reference to the ViewModel layer and notifies the ViewModel layer when business logic processing is required.
  • ViewModel layer, which is mainly responsible for the processing of business logic. The ViewModel layer does not involve any view manipulation. Through the officially provided Data Binding library, the data in the View layer and the ViewModel layer can be bound, and changes in the data in the ViewModel layer can automatically notify the View layer to update, so the ViewModel layer does not need to hold a reference to the View layer. The ViewModel layer can be seen as the combination of the data model of the View layer and the Presenter layer

The biggest difference between the MVVM pattern and the MVP pattern is that the ViewModel layer does not hold a reference to the View layer. This further reduces the coupling, and changes to the View layer code will not affect the ViewModel layer

The MVVM pattern has the following advantages over the MVP pattern:

  • Coupling is further reduced. The ViewModel layer does not hold a reference to the View layer. When the View layer changes, as long as the data bound to the View layer remains unchanged, the ViewModel layer does not need to be changed. In the MVP mode, when the View layer changes, the interface for operating the view needs to be changed accordingly, so the Presenter layer needs to be modified.
  • No more boilerplate code to write. Through the official Data Binding library, binding between UI and data can be achieved, and there is no need to write a lot of code for findViewById() and operation views. In short, the code of Activity/Fragment can be quite concise

1. Steps to use DataBinding:

  • enableDataBinding
  • Modify the layout file to the DataBinding layout
  • data binding

Second, use the MVVM framework steps:

  • Provide View, ViewModel and Model three layers
  • Modify the layout to DataBinding layout
  • Communication between View and ViewModel through DataBinding
  • Get data and display it on the interface

The full name of MVVM is Model (model) – View (view) – ViewModel (view model):

MVVM can be regarded as an upgraded version of MVP, changing Presenter to VIewModel. The key lies in the two-way binding between the View and the Model. When the View has user input, the ViewModel notifies the Model to update the data. Similarly, after the Model data is updated, the ViewModel notifies the View to update the data.

The advantages of MVVM are as follows:
1. The View and Model are bound in both directions. Changes in one side will affect the other side, so developers don't need to manually modify the UI data
. 2. No need to findViewById or butterknife, and no need to get a specific View to set Data binding listeners, etc., these can be completed with DataBinding
3. The two-way binding of View and Model supports life cycle detection, and there is no need to worry about page destruction and callbacks. This is done by lifeCycle.
4. It will not be like Like MVC, the amount of code in Activity is huge, and there will not be a large number of View and Presenter interfaces like MVP. Project structure is less coupled

what is databinding

DataBinding is a framework officially released by Google. As the name suggests, it is data binding. It is an implementation of the MVVM pattern on Android. It is used to reduce the coupling between layout and logic and make the code logic clearer.

Next, enter the topic
first to enable databinding:
The way to enable DataBinding is to add the following code to the build.gradle file of the corresponding Model. After synchronization, support for DataBinding can be introduced

android {
    
    
    ...
    dataBinding {
    
    
        enabled = true
    }
}

The following is a detailed introductionMVVM framework:

1. VM layer:
Here, according to the layout file activity_mvvmpattern of MVVMActivity, the Data Binding is introduced:

Data Binding still has certain requirements for the environment used: the Android Studio version is above 1.3, and the gradle version must be above 1.5.0-alpha1.
Need to download Android Support repository in Android SDK manager

Then add in the corresponding Module's build.gradle:

android {
    
    
  ....
  dataBinding {
    
    
      enabled =true
  }
}

Then use the databinding syntax to data bind the xml, we bind the Click event and the output result to the VM

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

    <data>
         <!--使用import来导入需要用的包-->
        <import type="android.view.View" />
         <!--使用关键字variable来声明一个变量,name为变量名,type为指向的对象,可以是类名也可以是类名的别名-->
        <variable
            name="userViewModel"
            type="com.mvvm.model.mvvm.viewmodel.MVVMDataViewModel" />

        <variable
            name="handlers"
            type="com.mvvm.model.mvvm.view.MVVMActivity" />
        <!--对于基本类型,可以像java代码一样不用去导入包,直接使用-->
        <variable
            name="data"
            type="String" />
    </data>

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

        <Button
            android:id="@+id/btnMVVM"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{handlers.onClickLoadData}"
            android:text="点击请求数据" />

        <Button
            android:id="@+id/btnToast"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{handlers.onClickShowToastName}"
            android:text="点击请求数据并Toast提示" />
            
        <!--使用变量-->
        <TextView
            android:id="@+id/tvData"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@{userViewModel.data}" />
    </LinearLayout>
</layout>

In the variable node defined in data, the name attribute represents the name of the variable, type represents the type of the variable, and the instance is the location of our entity class. Of course, you can also change this way here:

<data>
        <import type="android.view.View" />
        <variable
            name="userViewModel"
            type="com.mvvm.model.mvvm.viewmodel.MVVMDataViewModel" />
    </data>

BaseObservable, observable: Observer
or MVVMDataViewModel class as an example, BaseObservable provides two methods to refresh the UI, namely notifyPropertyChanged() and notifyChange()
   1. notifyPropertyChanged(); will only refresh the UI that belongs to it, just like code, it only refreshes Will update name
   2.notifyChange(); will refresh all UI

Bean class inherits BaseObservable
notifyPropertyChanged() needs to pass in a parameter of type int, which is int fieldId, which refers to the formal parameter name

Bindable is used to bind data to views
VM layer specific class: Note here that @Bindable needs to be added to specific attributes, otherwise the binding will be invalid

public class MVVMDataViewModel extends BaseObservable implements MVVMLoadDataCallback{
    
    
    private MVVMDataModel model;

    public MVVMDataViewModel() {
    
    
        model = new MVVMDataModel();
    }

    /**
     * 必须添加@Bindable注释
     * @return
     */
    @Bindable
    public String getData() {
    
    
        return model.mData;
    }

    public void loadUserData() {
    
    
        model.requestData(this);
    }

    @Override
    public void onSuccess() {
    
    
        notifyPropertyChanged(com.mvvm.model.BR.data);
    }

    @Override
    public void onFailure() {
    
    

    }
}

Select the BR under your own project or the third BR

2. The View layer (MVVMActivity) introduces the VM:

/**
 * View层
 */
public class MVVMActivity extends AppCompatActivity {
    
    
    private MVVMDataViewModel userViewModel;
    private TextView tvData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        ActivityMvvmpatternBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_mvvmpattern);
        userViewModel = new MVVMDataViewModel();
        binding.setUserViewModel(userViewModel);
        binding.setHandlers(this);

        tvData = binding.tvData;

    }

    public void onClickShowToastName(View view) {
    
    
        Toast.makeText(this, tvData.getText().toString(), Toast.LENGTH_LONG).show();
    }

    public void onClickLoadData(View view) {
    
    
        userViewModel.loadUserData();
    }
}

3. Model layer:
used for specific data request operations

/**
 * Model层
 */
public class MVVMDataModel {
    
    
    public String mData;
 
    public MVVMDataModel() {
    
    
        this.mData = "初始数据";
    }
 
    public void requestData(MVVMLoadDataCallback callback) {
    
    
        this.mData = "数据请求成功";
        callback.onSuccess();
    }
}

Although MVVM has these advantages, there are also many pits to use. Therefore, there are not many applications of the MVVM framework in actual development, mainly based on the development of the MVP framework.

Finally, provide the github source code for your reference: testMVVM

Guess you like

Origin blog.csdn.net/qq_35091074/article/details/123351470