Android開發MVVM設計模式的實現及ButterKnife相容結合原始碼詳解並總結優缺點

2020-10-16 12:00:48

MVVM設計模式主要是view通過中介軟體viewModel與model資料模型互動,咱們可以看一下流程圖:

本篇採用谷歌自帶DataBinding 元件實現MVVM,只需要在app.gradle開啟就行:

dataBinding {
    enabled = true
}

View佈局檔案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介面:

package com.freddy.chat;

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

View層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);
	}
}

業務層viewModel中介軟體:

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資料模型:

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();
    }
}

相容帶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優勢:

  1. UI層、業務層、資料層分工明確實現解耦,維護起來直接找準所需維護層大大減少了程式碼查詢時間以及維護困難;
  2. DataBinding採用了雙向繫結技術Model發生變化時View通過viewModel實現自動更新UI;
  3. Controller控制層直接拿到view層減少了控制層程式碼;

MVVM缺點:

  1. 由於view繫結了資料導致佈局無法複用;

你們的點贊、評論就是我更新文章的動力,希望我的文章輸出能幫助到一點正在努力中的你,大家一起加油哦!