作者: Dawish_大D
簡書: http://www.lxweimin.com/u/40e1f22c2c53
(一)Android官方MVVM框架實現組件化之整體結構
(二)Android官方MVVM框架實現組件化之ARouter串聯各模塊
目前的項目結構圖置頂:Demo的Github地址: https://github.com/Dawish/GoogleArchitectureDemo
在Google提供的MVVM
框架中,我認為DataBinding
才是最核心的一個,因為有了DataBinding
才可以使得數據跟UI綁定,甚至是雙向綁定,如果說之前的MVP可以輕量化View的重量,但是使用MVP還是得去寫一堆的findViewById
、一堆的View
或者是Presenter
接口,后來還出了一個contract
接口來連接View
和Presenter
接口。MVP的使用雖然可以解耦和拆分但是卻多出了很多接口。但是有了DataBinding
就不需要再使用findViewById
了,如果不是考慮統一性的需求,ViewModel
和View
之間也是不需要接口的,但是很多時候我們還是會做一些接口或者是抽象類來把一些共性的東西放在一起。
一、DataBinding基本使用
在build.gradle文件中開啟DataBinding功能:
android {
....
dataBinding {
enabled = true
}
}
是不是簡單得一批啊,要是MVVM
組件化中需要在每一個library
添加一下,有人說不需要用DataBinding
,但是用了這個最起碼不用再使用findViewById
方法了,所以還是加一下為好,又不要錢。
在我們的xml文件中改動很大,會有新的標簽使用,下面是一個基本的格式:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="google.architecture.common.ui.FragmentAbout">
<!--數據標簽-->
<data>
<!--import導入一些需要用到的類-->
<import type="java.util.List" />
<import type="google.architecture.common.ui.UserData" />
<!--申明需要用到的具體數據,name就是下面具體View使用時需要的變量名-->
<variable
name="userDataOF"
type="google.architecture.common.ui.UserDataOF"/>
<!--使用List集合,< > 就是 < > 的轉義符-->
<variable
name="userList"
type="List<UserData>" />
</data>
<!--UI布局-->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/size_20dp"
android:text="@{userList.get(0).userName}"
android:textSize="@dimen/text_size_20sp" />
</LinearLayout>
</layout>
從表面上看就是需要用的數據跟具體的xml布局文件綁定在一起了。在我上一篇的文章評論中有一個同學說到了kotlin
中有有庫可以使數據跟id綁定,我沒操作過,但是作用跟這個DataBinding
感覺類似。
不想寫了,更多關于DataBinding的內容請參考: https://developer.android.google.cn/topic/libraries/data-binding/index.html
我下面列舉沒列舉,官方文檔都說得很詳細了。官方文檔就是最好的博客資料,如果有文檔的話。
二、DataBinding支持集合數據
三、DataBinding支持雙向綁定
四、DataBinding自定義BindingAdapter
五、DataBinding在MVVM中的優勢
六、最后無恥的預告
下一篇我準備講講google
官方框架中的LifeCycle
,就是跟生命周期相關的一些東西。就是數據的處理是跟UI頁面生命周期綁定的,頁面消廢了是不會有數據回調的,也防止了內存泄漏。
決定不寫了,妹的,更新太快了,還不如學習別的。Databinding的文章官方的文章說的非常情況了,請看: https://developer.android.google.cn/topic/libraries/data-binding/index.html