(三)Android官方MVVM框架实现组件化之DataBinding

作者: Dawish_大D
简书: http://www.jianshu.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接口来连接ViewPresenter接口。MVP的使用虽然可以解耦和拆分但是却多出了很多接口。但是有了DataBinding就不需要再使用findViewById了,如果不是考虑统一性的需求,ViewModelView之间也是不需要接口的,但是很多时候我们还是会做一些接口或者是抽象类来把一些共性的东西放在一起。

一、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集合,&lt; &gt; 就是 < > 的转义符-->
        <variable
            name="userList"
            type="List&lt;UserData&gt;" />

    </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支持双向绑定

四、DataBinding自定义BindingAdapter

五、DataBinding在MVVM中的优势

六、最后无耻的预告
下一篇我准备讲讲google官方框架中的LifeCycle,就是跟生命周期相关的一些东西。就是数据的处理是跟UI页面生命周期绑定的,页面消废了是不会有数据回调的,也防止了内存泄漏。

决定不写了,妹的,更新太快了,还不如学习别的。Databinding的文章官方的文章说的非常情况了,请看: https://developer.android.google.cn/topic/libraries/data-binding/index.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。