移动 前端 Python Android Java

JetPacks之DataBinding

2020-06-27  本文已影响0人  zcwfeng

我们设计一个User,不断更新name,来作为入口进行DataBinding分析

关于使用,这里不介绍过多。官网查询即可。
注意gradle 配置 dataBiding true 即可

测试代码

<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
    <variable
        name="user"
        type="top.zcwfeng.jetpack.bean.User" />

</data>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <TextView
        android:id="@+id/tv"
        android:text="@{user.name}"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

上述就是我页面的layout

model User

public class User extends BaseObservable {
public String name;
-> 这个标签才能让我们进行绑定
@Bindable
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
    -> 系统会帮我们生成BR文件
    notifyPropertyChanged(BR.name);
}

public User(String name) {
    this.name = name;
}
}

Activity页面

public class SecondActivity extends AppCompatActivity {

ActivitySecondBinding activitySecondBinding;
User user;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_second);
    user = new User("David");
    activitySecondBinding = DataBindingUtil.setContentView(this,
            R.layout.activity_second);
    activitySecondBinding.tv.setText(user.getName());

    final Handler handler = new Handler();

    handler.post(new Runnable() {
        @Override
        public void run() {
            user.setName(user.name + "1");
//                activitySecondBinding.setUser(user);
            activitySecondBinding.setVariable(BR.user, user);
            Log.d("zcw:::", Thread.currentThread().getName());
            handler.postDelayed(this, 1000);
        }
    });
}
}

原理分析

------------------> layout 和 页面 自动生成两个xml 文件

我们的layout 和正常布局 在编译后:xml会自动进行分离

app/build/intermediates/data_binding_layout_info_type_merge/debug/out/activity_second-layout.xml
使我们的layout单独抽离的xml

app/build/intermediates/incremental/mergeDebugResources/stripped.dir/layout/activity_second.xml
这个是去掉layout标签内容的我们熟悉的布局文件

<?xml version="1.0" encoding="utf-8"?>

<Layout layout="activity_second" modulePackage="top.zcwfeng.jetpack" filePath="app/src/main/res/layout/activity_second.xml" directory="layout" isMerge="false" isBindingData="true" rootNodeType="androidx.constraintlayout.widget.ConstraintLayout">
    <Variables declared="true" type="top.zcwfeng.jetpack.bean.User" name="user">
        <location startLine="3" startOffset="8" endLine="5" endOffset="50"/>
    </Variables>
    <Targets>
        <Target tag="layout/activity_second_0" view="androidx.constraintlayout.widget.ConstraintLayout">
            <Expressions/>
            <location startLine="8" startOffset="4" endLine="24" endOffset="55"/>
        </Target>
        <Target id="@+id/tv" tag="binding_1" view="TextView">
            <Expressions>
                <Expression text="user.name" attribute="android:text">
                    <Location startLine="17" startOffset="12" endLine="17" endOffset="38"/>
                    <TwoWay>false</TwoWay>
                    <ValueLocation startLine="17" startOffset="28" endLine="17" endOffset="36"/>
                </Expression>
            </Expressions>
            <location startLine="15" startOffset="8" endLine="22" endOffset="55"/>
        </Target>
    </Targets>
</Layout>

-----------------> 代码入口
我们发现

-> 这两句话作用是一样的
activitySecondBinding.setUser(user)
activitySecondBinding.setVariable(BR.user, user);

系统帮我们生成的BR文件

public class BR {
  public static final int _all = 0;

  public static final int name = 1;

  public static final int user = 2;

  public static final int vm = 3;
}

一下三种情况会对应生成BR

1.xml中设置variable的name属性
2.VM继承BaseObservable,将某个成员变量加上@Bindable注解
3.VM继承BaseObservable,将get,set,is开头的方法加上@Bindable注解

进入setVariable 看源码结构,发现只有一个抽象方法的接口。实际上这种情况是APT 生成的代码实现。
build/generated/ap_generated_sources/debug/out/top/zcwfeng/jetpack/databinding/ActivitySecondBindingImpl.java

-> 最终还是调用了setUser
@Override
public boolean setVariable(int variableId, @Nullable Object variable)  {
    boolean variableSet = true;
    if (BR.user == variableId) {
        setUser((top.zcwfeng.jetpack.bean.User) variable);
    }
    else {
        variableSet = false;
    }
        return variableSet;
}

public void setUser(@Nullable top.zcwfeng.jetpack.bean.User User) {
    updateRegistration(0, User);
    this.mUser = User;
    synchronized(this) {
        mDirtyFlags |= 0x1L;
    }
    notifyPropertyChanged(BR.user);
    super.requestRebind();
}

updateRegisteration 方法

进入源码会发先,传入WeakListener 没有就创建一个监听器,这个监听器持有一个WeakPropertyListener 数组

进入了ViewDataBinding的updateRegisteration 方法做了两件事
如果传入的监听为null反注册-> unregisterFrom。然后创建对应BR中属性的监听
在进行->registerTo 方法操作。
不空的话。也是先 -> unregisterFrom 在注册->registerTo

private boolean updateRegistration(int localFieldId, Object observable,
        CreateWeakListener listenerCreator) {
    if (observable == null) {
        return unregisterFrom(localFieldId);
    }
    WeakListener listener = mLocalFieldObservers[localFieldId];
    if (listener == null) {
        registerTo(localFieldId, observable, listenerCreator);
        return true;
    }
    if (listener.getTarget() == observable) {
        return false;//nothing to do, same object
    }
    unregisterFrom(localFieldId);
    registerTo(localFieldId, observable, listenerCreator);
    return true;
}

----------------------> 另外的View 代码入口
DataBindingUtils.setContentView
DataBinderMapperImpl (返回ViewDataBinding控制)

关注一下代码里面-> 「说明」

@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);
    }
    case  LAYOUT_ACTIVITYSECOND: {

      ->这里是不是很熟悉,就是activity_second 拼接了BR文件的tag解析layout的布局文件

      if ("layout/activity_second_0".equals(tag)) {
        return new ActivitySecondBindingImpl(component, view);
      }
      throw new IllegalArgumentException("The tag for activity_second is invalid. Received: " + tag);
    }
  }
}
return null;
  }

代码 new ActivitySecondBindingImpl->invalidateALL
-> ViewDataBinding:requestRebind 刷新界面

但是UI是怎么填充
我们发现ViewDataBinding 有个静态块初始化了监听

ViewDataBinding-------->static 块

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) {
            }
        };
    }
}

执行了任务 mRebindRunnable
-> executePendingBindings()
-> executeBindings() 发现是abstract 方法
还是代码生成ActivitySecondImpl类里面

@Override
protected void executeBindings() {
    long dirtyFlags = 0;
    synchronized(this) {
        dirtyFlags = mDirtyFlags;
        mDirtyFlags = 0;
    }
    java.lang.String userName = null;
    top.zcwfeng.jetpack.bean.User user = mUser;

    if ((dirtyFlags & 0x7L) != 0) {



            if (user != null) {
                // read user.name
                userName = user.getName();
            }
    }
    // batch finished
    if ((dirtyFlags & 0x7L) != 0) {
        // api target 1

        androidx.databinding.adapters.TextViewBindingAdapter.setText(this.tv, userName);
    }
}
// Listener Stub Implementations
// callback impls
// dirty flag
private  long mDirtyFlags = 0xffffffffffffffffL;
/* flag mapping
    flag 0 (0x1L): user
    flag 1 (0x2L): user.name
    flag 2 (0x3L): null
flag mapping end*/
//end

}

发现了一个细节。之前我们初始化是 |= 将对应的 2的n次方位置变成1 证明我们更新。这次在& 操作判断是否为0,是0 证明之前更新1有问题。不是我们就更新界面

这块需要---------> 第三个入口 notifyPropertyChanged(BR.name);
这个在这个类里面实现,上面我们看到了这个类在监听回调中
PropertyChangeRegistry-> onPropertyChanged
WeakPropertyListener 中实现onPropertyChanged

 @Override
    public void onPropertyChanged(Observable sender, int propertyId) {
        ViewDataBinding binder = mListener.getBinder();
        if (binder == null) {
            return;
        }
        Observable obj = mListener.getTarget();
        if (obj != sender) {
            return; // notification from the wrong object?
        }
        binder.handleFieldChange(mListener.mLocalFieldId, sender, propertyId);
    }

handleFieldChange -》onFieldChange 一个抽象方法。

ActivitySecondBindingImpl - >onFieldChange 实现->onChangeUser-》

private boolean onChangeUser(top.zcwfeng.jetpack.bean.User User, int fieldId) {
    if (fieldId == BR._all) {
        synchronized(this) {
                mDirtyFlags |= 0x1L;
        }
        return true;
    }
    else if (fieldId == BR.name) {
        synchronized(this) {
                mDirtyFlags |= 0x2L;
        }
        return true;
    }
    return false;
}

整体的简图就是这样

DataBinding MVVM

总结:入口就是这个两个
setVariable(xxxx)
notifyPropertyChanged(BR.name);

上一篇下一篇

猜你喜欢

热点阅读