DataBinding做了什么

没有MVVM!没有MVVM!没有MVVM!

一、dataBinding用法

  1. app的build.gradle中添加依赖:
apply plugin: 'com.android.application'

android {
    ...
    // 引入DataBinding依赖
    dataBinding{
        enabled = true
    }
}

dependencies {
    ...
}
  1. 定义一个mode,两种写法是一样的l:
public class UserInfo {

public class UserInfo {

//    // 第一种方式  需要集成BaseObservable
//    private String username;
//
//    private String password;
//
//    @Bindable
//    public String getUsername() {
//        return username;
//    }
//
//    public void setUsername(String username) {
//        this.username = username;
//        notifyPropertyChanged(BR.username);
//    }
//
//    @Bindable
//    public String getPassword() {
//        return password;
//    }
//
//    public void setPassword(String password) {
//        this.password = password;
//        notifyPropertyChanged(BR.password);
//    }

    // 第二种方式
    public ObservableField<String> username = new ObservableField<>();
    public ObservableField<String> password = new ObservableField<>();
}

  1. 布局的写法要在外面包一层layout,并且配置data标签,配置要绑定的model对象
<?xml version="1.0" encoding="utf-8"?>
<!-- DataBinding编码规范 -->
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 定义该View(布局)需要绑定的数据来源 -->
    <data>
        <variable
            name="user"
            type="com.yu.databinding.model.UserInfo" />
    </data>

    <!-- 布局常规编码 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@={user.username}" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="@={user.password}" />
    </LinearLayout>
</layout>

name就类似一个别名、简称,type是要绑定的类的全名,用@={}进行双向绑定。

  1. 在Activity设置布局之前,要先build一下工程
public class MainActivity extends AppCompatActivity {

    private UserInfo userInfo = new UserInfo();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        userInfo.username.set("123");
        userInfo.password.set("456");
        binding.setUser(userInfo);

这样就完成了双向绑定,model数据修改会直接影响到view,view数据修改直接影响model。
用法完事,问题来了

  1. ActivityMainBinding是什么?
  2. DataBindingUtil.setContentView(xxx)做了什么,怎么实现的双向绑定?

二、dataBinding做了什么?

首先dataBinding会扫描布局文件,使用了dataBinding的布局会根据我们自己写的生成另外两个XML文件:


上图目录下这俩文件,注意是要build之后才生成的:
image.png

这俩文件是这样的,一个是用来布局的,只是多加了tag属性:
activity_main

第二个是把布局文件分解成了不同的Tag:
activity_mian-layout

然后看上面两个问题,先看DataBindingUtil.setContentView(xxx)做了什么,点进去追一下代码,在DataBindingUtil.java里:

    public static <T extends ViewDataBinding> T setContentView(@NonNull Activity activity,
            int layoutId, @Nullable DataBindingComponent bindingComponent) {
        activity.setContentView(layoutId);
        View decorView = activity.getWindow().getDecorView();
        ViewGroup contentView = (ViewGroup) decorView.findViewById(android.R.id.content);
        return bindToAddedViews(bindingComponent, contentView, 0, layoutId);
    }

这里先用activity.setContentView(layoutId);跟我们常规设置的没区别,然后用activity找到了decorView用于更新页面,关于DecorView看这里,然后继续跟bindToAddedViews:

    private static <T extends ViewDataBinding> T bindToAddedViews(DataBindingComponent component,
            ViewGroup parent, int startChildren, int layoutId) {
        final int endChildren = parent.getChildCount();
        final int childrenAdded = endChildren - startChildren;
        if (childrenAdded == 1) {
            final View childView = parent.getChildAt(endChildren - 1);
            return bind(component, childView, layoutId);
        } else {
            final View[] children = new View[childrenAdded];
            for (int i = 0; i < childrenAdded; i++) {
                children[i] = parent.getChildAt(i + startChildren);
            }
            return bind(component, children, layoutId);
        }
    }

这里都调用了一个叫bind的方法,不同的是一个传递的是View,一个传递的是View数组,继续跟:

    static <T extends ViewDataBinding> T bind(DataBindingComponent bindingComponent, View[] roots,
            int layoutId) {
        return (T) sMapper.getDataBinder(bindingComponent, roots, layoutId);
    }

    static <T extends ViewDataBinding> T bind(DataBindingComponent bindingComponent, View root,
            int layoutId) {
        return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);
    }

继续跟sMapper.getDataBinder发现这是个抽象类,看看在哪里实现了(方法是按option+command+B):

寻找实现类

很显然应该去我们自己的类里跟,那这里奇怪了,我们并没有写这个类,这个是Databinding里用APT技术自动生成的类:
APT生成文件目录

APT生成的文件都在这里,APT在这里简单介绍过,这里知道是自动生成文件的一种技术就行,跟进去这个getDataBinder方法,同样是两个实现,一个单个View的,一个View数组的:

@Override
  public ViewDataBinding getDataBinder(DataBindingComponent component, View view, int layoutId) {
    int localizedLayoutId = INTERNAL_LAYOUT_ID_LOOKUP.get(layoutId);
    if(localizedLayoutId > 0) {
      final Object tag = view.getTag();
      if(tag == null) {
        throw new RuntimeException("view must have a tag");
      }
      switch(localizedLayoutId) {
        case  LAYOUT_ACTIVITYMAIN: {
          if ("layout/activity_main_0".equals(tag)) {
            return new ActivityMainBindingImpl(component, view);
          }
          throw new IllegalArgumentException("The tag for activity_main is invalid. Received: " + tag);
        }
      }
    }
    return null;
  }

  @Override
  public ViewDataBinding getDataBinder(DataBindingComponent component, View[] views, int layoutId) {
    if(views == null || views.length == 0) {
      return null;
    }
    int localizedLayoutId = INTERNAL_LAYOUT_ID_LOOKUP.get(layoutId);
    if(localizedLayoutId > 0) {
      final Object tag = views[0].getTag();
      if(tag == null) {
        throw new RuntimeException("view must have a tag");
      }
      switch(localizedLayoutId) {
      }
    }
    return null;
  }

这里发现了从view里取tag的操作,下面这个实现只是检查了view是否有tag,上面这个实现中有个layout/activity_main_0,没错,就是上面自动生成的XML中的tag,然后返回了个ActivityMainBindingImpl的实现,这个文件也是自动生成的,点这个类继续追:

 public ActivityMainBindingImpl(@Nullable android.databinding.DataBindingComponent bindingComponent, @NonNull View root) {
        this(bindingComponent, root, mapBindings(bindingComponent, root, 3, sIncludes, sViewsWithIds));
    }
    private ActivityMainBindingImpl(android.databinding.DataBindingComponent bindingComponent, View root, Object[] bindings) {
        super(bindingComponent, root, 2
            );
        this.mboundView0 = (android.widget.LinearLayout) bindings[0];
        this.mboundView0.setTag(null);
        this.mboundView1 = (android.widget.EditText) bindings[1];
        this.mboundView1.setTag(null);
        this.mboundView2 = (android.widget.EditText) bindings[2];
        this.mboundView2.setTag(null);
        setRootTag(root);
        // listeners
        invalidateAll();
    }

这里发现调用了mapBindings得到一个数组,并且调用了重载函数,追一下这个mapBindings先,这个函数比较长,但是里面可以看出一些重点:

private static void mapBindings(DataBindingComponent bindingComponent, View view, Object[] bindings, ViewDataBinding.IncludedLayouts includes, SparseIntArray viewsWithIds, boolean isRoot) {
      ...
            if (isRoot && tag != null && tag.startsWith("layout")) {
               ...
            } else if (tag != null && tag.startsWith("binding_")) {
               ...

            if (!isBound) {
               ...
                    bindings[count] = view;
               ...
            }

           ...
    }

这里又发现一些熟悉的东西layoutbinding_,正是刚才XML中View的Tag,看到这里我们得出这个函数是把刚才的XML文件解析出的控件放进一个数组中,然后继续看上面那个重载函数,从数组中取出了这些控件,个这些控件取出的控件点一下看看,就是我们定义的一些控件:

    // views
    @NonNull
    private final android.widget.LinearLayout mboundView0;
    @NonNull
    private final android.widget.EditText mboundView1;
    @NonNull
    private final android.widget.EditText mboundView2;

然后调用了invalidateAll(),继续跟这个函数:

    @Override
    public void invalidateAll() {
        synchronized(this) {
                mDirtyFlags = 0x8L;
        }
        requestRebind();
    }

继续跟requestRebind()

    protected void requestRebind() {
       ...
            if (USE_CHOREOGRAPHER) {
                mChoreographer.postFrameCallback(mFrameCallback);
            } else {
                mUIThreadHandler.post(mRebindRunnable);
            }
        }
    }

这里的post(mRebindRunnable)跟下去会发现很多sendMessage的操作,这里就不贴了,
看看这个mRebindRunnable里做了什么,中间的过程不贴了,顺序跟下来是这样的:
executePendingBindings()->executeBindingsInternal()->executeBindings(),这个executeBindings是抽象的,需要看自己的实现:

    @Override
    protected void executeBindings() {

        ...

        // batch finished
        if ((dirtyFlags & 0xdL) != 0) {
            // api target 1

            android.databinding.adapters.TextViewBindingAdapter.setText(this.mboundView1, userUsernameGet);
        }
        if ((dirtyFlags & 0x8L) != 0) {
            // api target 1

            android.databinding.adapters.TextViewBindingAdapter.setTextWatcher(this.mboundView1, (android.databinding.adapters.TextViewBindingAdapter.BeforeTextChanged)null, (android.databinding.adapters.TextViewBindingAdapter.OnTextChanged)null, (android.databinding.adapters.TextViewBindingAdapter.AfterTextChanged)null, mboundView1androidTextAttrChanged);
            android.databinding.adapters.TextViewBindingAdapter.setTextWatcher(this.mboundView2, (android.databinding.adapters.TextViewBindingAdapter.BeforeTextChanged)null, (android.databinding.adapters.TextViewBindingAdapter.OnTextChanged)null, (android.databinding.adapters.TextViewBindingAdapter.AfterTextChanged)null, mboundView2androidTextAttrChanged);
        }
        if ((dirtyFlags & 0xeL) != 0) {
            // api target 1

            android.databinding.adapters.TextViewBindingAdapter.setText(this.mboundView2, userPasswordGet);
        }
    }

bulingbuling~~看到了什么?setText()setTextWatcher()

这个代码跟完之后,还有个地方需要注意的,就是这个类的静态块:

    private static final OnAttachStateChangeListener ROOT_REATTACHED_LISTENER;

    static {
        if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
            ROOT_REATTACHED_LISTENER = null;
        } else {
            ROOT_REATTACHED_LISTENER = new OnAttachStateChangeListener() {
                @TargetApi(VERSION_CODES.KITKAT)
                @Override
                public void onViewAttachedToWindow(View v) {
                    // execute the pending bindings.
                    final ViewDataBinding binding = getBinding(v);
                    binding.mRebindRunnable.run();
                    v.removeOnAttachStateChangeListener(this);
                }

                @Override
                public void onViewDetachedFromWindow(View v) {
                }
            };
        }
    }

这里有个OnAttachStateChangeListener,也就是每个Activity都会有一个监听View变化的,一旦有view变化,会调用mRebindRunnable.run()mRebindRunnable上面已经跟过,是做刷新用的,也就是每个Activity都会有一个Runnable去做刷新工作。

代码到这里看差不多了,有些没贴到没说到或者迷糊的地方进去点点,这里的代码量并不大。
但是看代码的过程也发现了一些问题,就是内存的开销,其中主要有这么几点:

  1. 有一个数组去存储这些控件
  2. ActivityMainBindingImpl这个类对应有个Runnable负责刷新
  3. 还看到一行这样的代码mUIThreadHandler.post(mRebindRunnable),这个mUIThreadHandler也是一个Handler,Handler内部的Looper也会维持一个线程

这个ActivityMainBindingImpl是根据使用了Databinding的布局文件生成的,每一个是用了Databinding的布局都会生成这么一个文件,也可以理解问每一个Activity就会对应一个数组和两个线程,数组的大小是该布局控件数量决定的。

随着项目越来越大,使用Databinding的缺点也就越来越明显:

  1. APT需要生成的文件也越来越多,编译就会越来越慢
  2. 内存消耗越来越大

项目地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,193评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,306评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,130评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,110评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,118评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,085评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,007评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,844评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,283评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,508评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,667评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,395评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,985评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,630评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,797评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,653评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,553评论 2 352

推荐阅读更多精彩内容