DataBinding基本原理解析
知其然,知其所以然。了解原理之后会帮助我们在使用过程中遇到问题能够定位的更准确,速度更快一点。所以搞了一波DataBinding的原理,记录下来,方便以后查阅。
DataBinding流程原理.png
Step1处理Layout(这里以activity_main.xml为例)
1)抽出表达式及Variables生成activity_main-layout.xml,同时也会给用到表达式的view添加tag
2)剩下的部分activity会给最底层的Layout和带有表达式的View添加tag(此处的tag和上面的tag一一对应),其余部分和正常的layout没有区别了。
注意:这里的tag,在给view进行初始化的时候会用到。
这里没有上代码对比,可以去工程下build->intermediates->classes、data-binding-info及data-binding-layout-out中去找和你的binding layout对应上述几个文件自行对比。
Step2生成ActivityDemoBinding类和BR类
生成ActivityDemoBinding类,同时Variables变量都会在该类中声明为
Private BindingDemoBean mDemoBean;
没有ID,添加了tag(处理layout时候添加的)的View会声明为
private final Button mboundView1;
设置了ID的View,会声明为
public final TextView tvId;
public final TextView tvName;
public final TextView tvSchool;
生成BR类:
public class BR {
public static final int _all = 0;
public static final int demoBean = 3;
public static final int includeBean = 4;
...
public static final int presenter = 9;
public static final int school = 10;
...
public BR() {
}
}
_all是默认生成的,其他的都是我们在如下几种情况生成的。
<variable
name="demoBean"
... />
<variable
name="includeBean"
... />
@Bindable
public String getSchool() {
return school;
}
分别是代表这些变量的标志,比如我们想单独更新school的话就可以通过BR.school单独对使用school的View进行数据更新:
mBinding.setVariable(BR.school,"厉害了");
Step3生成ActivityDemoBinding实例
这里要从
DataBindingUtil.setContentView(this, R.layout.activity_main);
出发:
//调用Activity的setContentView,然后取出作为View传递bindToAddedViews
public static <T extends ViewDataBinding> T setContentView(Activity activity, int layoutId,
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);
}
//然后这里是判断如果我们的layout只有一个和多个子View的情况下去bind
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);
}
}
//判断当前我们的layout是不是一个binding layout
public static <T extends ViewDataBinding> T bind(View root,
DataBindingComponent bindingComponent) {
T binding = getBinding(root);
if (binding != null) {
return binding;
}
Object tagObj = root.getTag();
if (!(tagObj instanceof String)) {
throw new IllegalArgumentException("View is not a binding layout");
} else {
String tag = (String) tagObj;
int layoutId = sMapper.getLayoutId(tag);
if (layoutId == 0) {
throw new IllegalArgumentException("View is not a binding layout");
}
return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);
}
}
//然后根据R.layout.activity_main这个layoutId来作为标志返回具体的Binding类,这里我们跟进case com.thc.bindingdemo.R.layout.activity_main:
public android.databinding.ViewDataBinding getDataBinder(android.databinding.DataBindingComponent bindingComponent, android.view.View view, int layoutId) {
switch(layoutId) {
case com.thc.bindingdemo.R.layout.fragment:
return com.thc.bindingdemo.databinding.CustomBindingName.bind(view, bindingComponent);
case com.thc.bindingdemo.R.layout.activity_main:
return com.thc.bindingdemo.databinding.ActivityMainBinding.bind(view, bindingComponent);
case com.thc.bindingdemo.R.layout.include_test:
return com.thc.bindingdemo.databinding.IncludeTestBinding.bind(view, bindingComponent);
case com.thc.bindingdemo.R.layout.item_recyclerview:
return com.thc.bindingdemo.databinding.ItemRecyclerviewBinding.bind(view, bindingComponent);
case com.thc.bindingdemo.R.layout.activity_demo2:
return com.thc.bindingdemo.databinding.ActivityDemo2Binding.bind(view, bindingComponent);
case com.thc.bindingdemo.R.layout.activity_test_bind_recycler:
return com.thc.bindingdemo.databinding.ActivityTestBindRecyclerBinding.bind(view, bindingComponent);
}
return null;
}
//这里调用了ActivityMainBinding的构造方法,将我们的layout View作为参数
public static ActivityMainBinding bind(android.view.View view, android.databinding.DataBindingComponent bindingComponent) {
if (!"layout/activity_main_0".equals(view.getTag())) {
throw new RuntimeException("view tag isn't correct on view:" + view.getTag());
}
return new ActivityMainBinding(bindingComponent, view);
}
到这里,ActivityMainBinding类的实例就生成了。虽然生成了实例,但是layout中的View是在啥时候初始化的呢,我们去ActivityMainBinding的构造方法看一眼:
public ActivityMainBinding(android.databinding.DataBindingComponent bindingComponent, View root) {
super(bindingComponent, root, 3);
final Object[] bindings = mapBindings(bindingComponent, root, 25, sIncludes, sViewsWithIds);
this.activityMain = (android.widget.LinearLayout) bindings[1];
this.activityMain.setTag(null);
this.includeBar = (com.thc.bindingdemo.databinding.IncludeTestBinding) bindings[24];
this.iv1 = (android.widget.ImageView) bindings[15];
this.iv1.setTag(null);
this.iv2 = (android.widget.ImageView) bindings[16];
this.iv2.setTag(null);
this.mboundView0 = (android.widget.ScrollView) bindings[0];
this.mboundView0.setTag(null);
this.mboundView17.setTag(null);
...
this.tvClassName.setTag(null);
this.tvName = (android.widget.TextView) bindings[4];
this.tvName.setTag(null);
this.tvSchool = (android.widget.TextView) bindings[6];
this.tvSchool.setTag(null);
setRootTag(root);
// listeners
mCallback1 = new android.databinding.generated.callback.OnClickListener(this, 1);
invalidateAll();
}
删除了部分元素。这里强行解释一波吧,就是在mapBindings中对ViewGroup进行了遍历初始化,然后放到bindings[]这个View数组中,然后再给已经在ActivityMainBinding类中声明的View进行赋值,同时清除tag。所以,这里是一次性把所有的View进行声明赋值,比findViewById一次就遍历一次ViewGroup更节省性能。
Setp4设置数据
我们可以看到在ActivityMainBinding的构造方法最后调用了invalidateAll(),这是干啥的呢,绑定数据嘛,看一下就知道了:
@Override
public void invalidateAll() {
synchronized(this) {
mDirtyFlags = 0x1000L;
}
includeBar.invalidateAll();
requestRebind();
}
/**
* 首先判断Api版本,在大于16的情况下就会给mUIThreadHandler post一个Runable,
*这个Runable
* 从名字也可以看出,mUiThreadHandler是UI线程的Handler嘛,
* 所以,DataBinding允许我们在子线程中设置数据,是因为这里它做了切换到UI线程更新数据的操作。
*/
protected void requestRebind() {
synchronized (this) {
if (mPendingRebind) {
return;
}
mPendingRebind = true;
}
if (USE_CHOREOGRAPHER) {
mChoreographer.postFrameCallback(mFrameCallback);
} else {
mUIThreadHandler.post(mRebindRunnable);
}
}
private final Runnable mRebindRunnable = new Runnable() {
@Override
public void run() {
....
executePendingBindings();
}
};
public void executePendingBindings() {
...
//每个继承ViewDataBinding的Binding类会重写这个方法,看一下我们的ActivityMainBinding
executeBindings();
...
}
//ActivityMainBinding 的executeBindings方法(删除了很多,只是拿了两个来做说明)。
protected void executeBindings() {
long dirtyFlags = 0L;
synchronized(this) {
dirtyFlags = this.mDirtyFlags;
this.mDirtyFlags = 0L;
}
//定义了两个变量来接收表达式的值
String nameDemoBean = null;
String schoolDemoBean = null;
BindingDemoBean demoBean = this.mDemoBean;
if((dirtyFlags & 7L) != 0L) {
if((dirtyFlags & 5L) != 0L && demoBean != null) {
//取出表达式的值
nameDemoBean = demoBean.getName();
}
if(demoBean != null) {
schoolDemoBean = demoBean.getSchool();
}
}
if((dirtyFlags & 5L) != 0L) {
//然后给这个TextView赋值
/**
* 这个TextViewBindingAdapter是DataBinding自定义的BindAdapter,
* 如果系统不自定义这个BindAdapter,
* 应该是直接找到该View的setter方法 即:tvName.setText(nameDemoBean)设置数据,就ok了。
*/
TextViewBindingAdapter.setText(this.tvName, nameDemoBean);
}
if((dirtyFlags & 7L) != 0L) {
TextViewBindingAdapter.setText(this.tvSchool, schoolDemoBean);
}
}
到这里从开始处理Layout,生成ActivityMainBinding类,初始化这个类,然后绑定数据就完成了。
DataBindingUtil.inflate(...)同上。
事件绑定及其他一些待补充吧。