Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android MVVM 與 DataBinding 實戰入門:讓數據自己驅動界面

編輯:關於 Android 開發

MVVM 是一種架構模式,DataBinding 是一個實現數據與 UI 綁定的框架。兩者結合之後,ViewModel 與 View 之間可以建立單向或雙向綁定,界面隨數據變化而自動刷新——這套動態監聽與更新機制,Google 已經幫我們封裝好了。MVVM 的思想與 MVP 頗為相似,差別在於 ViewModel 與 View 是靠「綁定」而非「接口回調」來協作。

一、三個角色的職責邊界

View:不做任何業務邏輯,不碰數據的處理與操作,職責就是展示,把 UI 和數據徹底分離。

Model:實體模型,同時包括 Retrofit 的 Service。它負責提供數據源,例如返回一個 Observable<Bean>(RxJava)。

ViewModel:承接 View 與 Model 之間的交互,承擔業務邏輯。它做的事恰好與 View 相反:只處理業務邏輯與業務數據,不持有任何控件的引用,也不會通過 UI 對象去更新界面。數據綁定在相應控件上之後,UI 更新會自動發生。

一句話記住:ViewModel 不做任何和 UI 相關的事。

二、MVVM 的優勢

  • 低耦合:數據獨立於 UI。ViewModel 只負責處理和提供數據,UI 如何呈現由 View 自己決定。即使控件替換,ViewModel 幾乎不需要改動。
  • 更新 UI 更簡單:只要數據是線程安全的,可以直接在工作線程修改 ViewModel 的數據,剩下的交給綁定框架,不必手動 runOnUiThread 或 post 到主線程。
  • 可複用:同一個 ViewModel 可以服務多個 View。同一份數據用不同 UI 展示,遇到頻繁的 UI 迭代只需替換 View 層;想做 A/B Test 更是輕鬆。
  • 易測試:ViewModel 裡是數據和業務邏輯,View 裡關注 UI,兩者互不依賴,UI 單元測試與業務邏輯單元測試都能獨立進行。

三、三者如何協作

Model 通過 Retrofit 獲取網絡數據,返回 Observable<Bean>,這就是它做的全部。ViewModel 則是:接收參數調用 Model 取數據(數據庫同理),把 Model 中的部分字段映射到自己的 ObservableField 上,並保留 Model 的引用,最後這些字段被綁定到 View 的控件上。

四、工程配置

在项目根目錄的 build.gradle 中添加:

classpath 'com.android.tools.build:gradle:1.2.3'
classpath 'com.android.databinding:dataBinder:1.0-rc0'

在需要使用 DataBinding 的模塊 build.gradle 中應用插件:

apply plugin: 'com.android.databinding'

五、佈局文件:根節點與 data 節點

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

    <data>
        <variable
            name="viewModel"
            type="cn.saiz.mvvmhello.MainViewModel"/>
    </data>

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:textSize="16sp"
                android:textColor="@android:color/black"
                android:gravity="center"
                android:text="用戶名:"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="simon"
                android:text="@={viewModel.userName}"
                app:addTextChangedListener="@{viewModel.userNameEditTextWatcher}"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:textSize="16sp"
                android:textColor="@android:color/black"
                android:gravity="center"
                android:text="密碼:"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="123456"
                android:text="@={viewModel.passWord}"
                app:addTextChangedListener="@{viewModel.passwordEditTextWatcher}"/>
        </LinearLayout>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{viewModel.login}"
            android:text="登錄"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="注冊"/>
    </LinearLayout>
</layout>

兩個顯著變化:根節點變成了 layout,並多了一個 data 節點。

data 節點是數據與 UI 之間的橋樑。在其中聲明一個 variable,該變量會為 UI 元素提供數據,再在代碼裡把「後台」數據綁定上去。

name 可以隨意命名;type 填的是 Java 中定義的 ViewModel 類全路徑。

前面添加的 com.android.databinding 插件會根據 XML 文件名稱生成一個繼承自 ViewDataBinding 的類。這裡文件叫 activity_main.xml,生成的類就是 ActivityMainBinding。

注意綁定表達式的兩種寫法:@{...} 是單向綁定,@={...} 是雙向綁定——輸入框的內容變化會同步回 ViewModel 的字段。

六、代碼中完成綁定

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ViewDataBinding binding =
            DataBindingUtil.setContentView(this, R.layout.activity_main);
    binding.setVariable(cn.saiz.mvvmhello.BR.viewModel, new MainViewModel(this));
}

綁定完成後,佈局裡的表達式就能正常工作了。

七、小結

MVVM 的門檻在於思維方式的轉變:習慣了在 Activity 裡 findViewById、setText、addTextChangedListener 之後,要忍住不寫這些代碼並不容易。但一旦貫徹「ViewModel 不碰 UI」這條紀律,好處會很快顯現——可測、可複用、UI 改動成本大幅下降。有興趣的同學可以進一步把 MVVM 與 MVP、MVC 做對比,再結合 Jetpack 的 ViewModel、LiveData 一起使用,會是更現代也更省心的方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved