/>
</androidx.constraintlayout.widget.ConstraintLayout>
这个文件其实就是移除了<layout>、<data>
标签的布局文件,里面的 tag 就是我们上面对应<Target>
标签中的tag
,Expression attribute="android:text" text="userInfo.age"
<Expression>
中的具体属性对应具体的值。
初始化
再来从val activityBinding: ActivityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main)
来分析源码,
//DataBindingUtil.java
public static T setContentView(@NonNull Activity activity,
int layoutId, @Nullable DataBindingComponent bindingComponent) {
activity.setContentView(layoutId); //还是需要setContentView
View decorView = activity.getWindow().getDecorView();
ViewGroup contentView = (ViewGroup) decorView.findViewById(android.R.id.content);
return bindToAddedViews(bindingComponent, contentView, 0, layoutId);
}
我们设置的activity_xxx.xml
其实是在android.R.id.content
下面的,继续来看bindToAddedViews
方法
//DataBindingUtil.java
private static 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); //调用bind
} 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
}
}
}
最终会调到bind
方法
//DataBindingUtil.java
static T bind(DataBindingComponent bindingComponent, View root,
int layoutId) {
return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);
}
sMapper
是DataBinderMapper
,其真正实现类是通过 APT 生成的DataBinderMapperImpl(app/build/generated/ap_generated_sources/debug/out/com/jackie/jetpackdemo/DataBinderMapperImpl.java)
public class DataBinderMapperImpl extends DataBinderMapper {
···
@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); //关键代码,new ActivityMainBindingImpl
}
···
接下来我们来分析ActivityMainBindingImpl(app/build/generated/ap_generated_sources/debug/out/com/jackie/jetpackdemo/databinding/ActivityMainBindingImpl.java)
这个类,它也是 APT 生成的,
//ActivityMainBindingImpl.java
public ActivityMainBindingImpl(@Nullable androidx.databinding.DataBindingComponent bindingComponent, @NonNull View root) {
this(bindingComponent, root, mapBindings(bi