The realization and compatibility of Android development MVVM design pattern combined with source code detailed explanation and summary of advantages and disadvantages

The MVVM design pattern is mainly that the view interacts with the model data model through the middleware viewModel. Let's look at the flowchart:

This article uses Google's own DataBinding component to implement MVVM, just open it in app.gradle:

dataBinding {
    enabled = true
}

View layout file xml:

<?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 type="com.freddy.chat.MainViewModel"/>
        <variable
            name="viewModel"
            type="MainViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{viewModel.getData}"
            android:text="测试" />

        <TextView
            android:id="@+id/tv_test"
            android:layout_width="200dp"
            android:layout_height="50dp"
            android:layout_marginLeft="20dp"
            android:text="@{viewModel.model.name}" />
    </LinearLayout>
</layout>

View interface:

package com.freddy.chat;

/**
 * Created by xie on 2020/10/15.
 */
public interface MainView {
    void moveText(int offset);
}

View layer Activity:

public class MainActivity extends AppCompatActivity implements  MainView {
	private ActivityMainBinding binding;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
 		binding.setViewModel(new MainViewModel(this));

	}
	@Override
	public void moveText(int offset) {
        binding.tvTest.setTranslationX(offset);
	}
}

Business layer viewModel middleware:

package com.freddy.chat;

import android.view.View;

/**
 * Created by xie on 2020/10/14.
 */
public class MainViewModel {
    private String name = "测试";
    private MainModel model;
    private MainView view;


//    @BindingAdapter("android:text")
//    public static void onTextChange(TextView view, CharSequence text) {
//        Log.e("tag", String.valueOf(text));
//    }


    public MainViewModel(MainView view) {
        this.view = view;
        this.model = new MainModel();
        model.setName(name);
    }

    public MainModel getModel() {
        return model;
    }

    public void getData(View v) {
        model.setName("MVVM测试");
        view.moveText(100);
    }
}

Model data model:

package com.freddy.chat;

package com.freddy.chat;

import android.databinding.BaseObservable;
import android.databinding.Bindable;

import com.android.databinding.library.baseAdapters.BR;

/**
 * Created by xie on 2020/10/14.
 */
public class MainModel extends BaseObservable {
    private String name;

    @Bindable
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);//刷新指定属性UI,刷新所有属性采用notifyChange();
    }
}

Compatible with the old version of ButterKnife:

protected abstract boolean isMvvM();

if (!isMvvM()) {
    ButterKnife.bind(this);
}
protected View getContentView() {
    View root = LayoutInflater.from(this).inflate(R.layout.activity_base, null);
    FrameLayout content = (FrameLayout) root.findViewById(R.id.content_frame);
    View contentView = LayoutInflater.from(this).inflate(getContentResource(), null);
    content.addView(contentView);
    if (isMvvM()) binding = DataBindingUtil.bind(contentView);
    return root;
}

public <T extends ViewDataBinding> T getBinding() {
    return (T) binding;
}

MVVM advantages:

  1. The UI layer, business layer, and data layer are clearly decoupled, and the required maintenance layer is directly identified during maintenance, which greatly reduces the code search time and maintenance difficulties;
  2. DataBinding uses two-way binding technology when the Model changes, the View realizes the automatic update of the UI through the viewModel;
  3. The Controller control layer directly gets the view layer to reduce the control layer code;

Disadvantages of MVVM:

  1. The layout cannot be reused because the view is bound to data;

Your likes and comments are my motivation to update the article. I hope that the output of my article can help you who are working hard. Come on together!

Guess you like

Origin blog.csdn.net/xhf_123/article/details/109097954