Android Data Binding(一)

作者: 慕涵盛华 | 来源:发表于2017-04-18 18:17 被阅读89次

    目录

    1.简介
    2.基础用法
    3.原理
    4.高级应用

    一.简介

    什么是DataBinding

    DataBinding,数据绑定,可以直接在xml中绑定数据并实现一些处理逻辑,实时动态刷新数据。它的功能强大,可以节省很多手写的代码,而且性能也很好。是基于MVVM提出的。DataBinding是一个实现数据和UI绑定的框架,是构建MVVM模式的一个工具。

    MVVM

    <b>View:</b> 对应于Activity和XML,负责View的绘制以及与用户交互。
    <b>Model:</b> 实体模型。
    <b>ViewModel:</b> 负责完成View与Model间的交互,负责业务逻辑。

    基本用途

    • 去掉Activity和Fragment中的UI代码
    • XML变成UI唯一的真实来源
    • 减少定义View id,即减少findViewById()

    优势和劣势

    主要优势

    • 去掉Activity和Fragment中的UI代码
    • 性能超过手写的代码,安全(不会因为id而crash)
    • 保证在主线程中执行

    劣势

    • IDE支持还不完善
    • 报错信息不那么直接
    • 没有重构支持

    二.基本用法

    <b>第一步:</b>配置gradle

    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.2"
    
        dataBinding{
            enabled = true  //设置支持dataBinding
        }
    ..........
    }
    

    <b>第二步:</b>layout文件修改 ,在常规的布局的基础上在最外层添加一个<layout></layout>标签

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"/>
        
            <TextView
                android:id="@+id/tv_sex"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"/>
       
        </LinearLayout>
    </layout>
    

    <b>第三步:</b>如果正常的话就会生成一个对应的Binding类,使用DataBindingUtil替换掉setContentView()

    public class DemoActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ActivityDemoBinding binding = DataBindingUtil.setContentView(DemoActivity.this,
                    R.layout.activity_demo);
        }
    }
    

    <b>第四步:</b>使用生成的binding对象可以直接获取控件,从而避免findViewById()

    binding.tvName.setText("慕涵盛华");
    binding.tvSex.setText("男");
    

    <b>名字生成规则:</b>

    • Binding类是根据布局文件的名字生成的: activity_demo --> ActivityDemoBinding
    • 控件的名字是根据id生成的:tv_name -- > tvName

    效果图:

    效果图

    UI绑定

    在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>
            <variable
                name="person"    <!-- 指定名字,下面通过该名字引用对应的数据 -->
                type="com.gfd.demo.entity.Person"/>  <!-- 指定绑定的实体类-->
        </data>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="@{person.name}"/> <!-- 关联实体类中的name数据-->
    
            <TextView
                android:id="@+id/tv_sex"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="@{person.sex}"/> <!-- 关联实体类中的sex数据-->
    
         </LinearLayout>
    </layout>
    

    在代码中无需使用控件设置数据

    public class DemoActivity extends AppCompatActivity {
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ActivityDemoBinding binding = DataBindingUtil.setContentView(DemoActivity.this,
                  R.layout.activity_demo);
            Person person = new Person("慕涵盛华","男");
            binding.setPerson(person);//将数据关联到xml
            //binding.setVariable(com.gfd.demo.BR.person,person);//将数据关联到xml
        }
    }
    

    实现的效果与上面的一样 , binding.setPerson()方法是自动生成的 是根据 <variable
    name="person" /> 中的name属性来命名的

    事件绑定

    按钮点击事件,文本改变监听等,事件绑定又分为两种方式:

    第一种方式:函数调用

    <b>第一步:</b>在代码中定义事件相关的类,类中的方法一定要跟事件发生调用的方法一样,例如:如果是按钮点击事件 那么方法的定义必须为:public void onClick(View view){.........}

    /** 事件监听类 */
    public class Presenter {
    
        /**
         * 文本改变监听
         * @param s
         * @param start
         * @param before
         * @param count
         */
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //将输入的内容显示到TextView上
            binding.tvName.setText(s.toString());
        }
    
        /**
         * 点击事件
         * @param view
         */
        public void onClick(View view) {
            Toast.makeText(DemoActivity.this, "按钮被点击", Toast.LENGTH_SHORT).show();
        }
    }
    

    <b>第二步:</b>在xml中将事件与UI绑定

    <?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>
            <variable
                name="presenter"
                type="com.gfd.demo.DemoActivity.Presenter"/><!-- 指定对应的类 -->
        </data>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="#f5ac2e">
    
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入内容"
                android:onTextChanged="@{presenter.onTextChanged}"<!-- 关联事件  -->
                android:padding="10dp"/>
    
            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp" />
    
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="点击演示"
                android:onClick="@{presenter.onClick}" <!-- 关联事件  -->
                android:layout_gravity="center"/>
    
        </LinearLayout>
    </layout>
    

    最后在代码中关联xml

     binding.setPresenter(new Presenter());
    

    效果如下:

    演示.gif

    第二种方式:监听器

    使用监听器的方式我们可以在事件发生的时候传递任何的数据,但是在xml中语法会复杂一些

    方法定义如下:

     /**
       * 以监听器的方式设置点击监听
       * @param person :传递的参数我们可以随意的指定
     */
    public void onClickListenerBinding(Person person){
        Toast.makeText(DemoActivity.this, person.getName(), Toast.LENGTH_SHORT).show();
    }
    

    xml定义如下:

    <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:textSize="20sp"
         android:text="@{person.name}"
         android:onClick="@{() -> Presenter.onClickListenerBinding(persom)}"/> <!-- 在点击的时候传递数据-->
    

    三.DataBinding的原理

    相关的类

    • android.binding
    • BR :跟R类似,指向的是bindingresource
    • XXXXBinding :自动生成的一些binding类
    原理图解

    我们通过查看XXXXBinding类的源码来分析一下它的实现过程

    1.png

    在该方法中会回去根View,然后调用bindToAddedViews()方法,下面看一下次方法做了什么操作

    2.png

    在该方法中最后都会调用bind方法

    3.png

    在bind方法中会先判断tag是否正确(tag是自动生成的,如果不手动改动的话是不会报错的),如果没有错误的话就会调用创建一个XXXXBinding对象,在构造方法中最终会调用mapBindings方法,下面看一下次方法中做的操作

    4.png

    mapBindings方法中会遍历所有的布局中的view,然后添加到数组中

    5.png

    然后在数组中找到对应的View

    在设置数据的时候是怎么设置到对应的View上的呢?


    6.png

    在该方法中先接受传递过来的数据,然后通知数据改变,在数据改变的方法中就就会调用下面的代码,从而将数据设置到对应的View上

    a7.png

    性能高的原因

    通过上面源码的分析我们可以总结一下几点:

    • 1.没有使用反射
    • 2.findViewById需要遍历整个ViewGroup,现在只需要做一次,直接通过数组的下标来获取
    • 3.使用位标记来检查更新(即mDirtyFlags)
    • 4.缓存了表达式(如果同一表达式计算过,下次直接使用)

    关注微信公众号获取更多相关资源

    Android小先生

    相关文章

      网友评论

        本文标题:Android Data Binding(一)

        本文链接:https://www.haomeiwen.com/subject/qdrfzttx.html