我的博客php
在須要使用DataBinding的模塊的build.gradle中增長android
android {
//...
defaultConfig {
//...
dataBinding{
enabled true
}
}
}
複製代碼
而後同步api
新建一個繼承自BaseObservable
的類app
public class User extends BaseObservable {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(com.wangyz.jetpack.BR.name);
}
@Bindable
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
notifyPropertyChanged(com.wangyz.jetpack.BR.age);
}
}
複製代碼
在須要綁定的字段的get
方法上增長@Bindable
註解,在set方法裏增長notifyPropertyChanged(com.wangyz.jetpack.BR.name)
ide
build工程佈局
新建佈局文件,在佈局最外層的節點上按alt+enter
,在彈出的選項中選擇Convert to data binding layout
,佈局就會轉換成DataBinding格式的佈局。post
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.wangyz.jetpack.databinding.User" />
</data>
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<Button android:onClick="update" android:text="更新" android:layout_width="match_parent" android:layout_height="50dp"/>
<TextView android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center_vertical" android:text="@{user.name}" />
<TextView android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center_vertical" android:text="@{String.valueOf(user.age)}" />
</LinearLayout>
</layout>
複製代碼
轉換後的佈局,會將layout
做爲最外層的節點,還會在裏面增長一個data
節點。咱們須要在這個data節點中增長variable
節點,並配置name
和type
屬性。name命名隨意,type輸入前面定義的User
類。學習
對須要綁定的控件屬性,如text賦值爲@{user.name}
,意思是給text屬性賦值爲前面綁定的User類的name。這樣當User的name發生改變時,控件的text屬性就會自動改變。gradle
在Activity中綁定User和佈局
public class DataBindingActivity extends AppCompatActivity {
User user;
ActivityDatabindingBinding binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_databinding);
user = new User("張三", 18);
binding.setUser(user);
}
public void update(View view) {
user.setName(user.getName() + "$");
user.setAge(user.getAge() + 1);
binding.setVariable(com.wangyz.jetpack.BR.user, user);
}
}
複製代碼
經過DataBindingUtil.setContentView(this, R.layout.activity_databinding)
來綁定,並返回Binding
,而後經過Binding的setUser
方法,就能夠給佈局設置數據。
下面來看下原理。DataBinding相比前面的Lifecycle
和LiveData
要複雜。
咱們將應用運行到手機上,這個在開發者看來是很簡單的一件事,可是Android Studio卻爲咱們作了不少事。
首先,佈局文件會分爲兩個xml文件。
在app/buil/intermediates/data_binding_layout_info_type_merge/debug/mergeDebugResources/out/
目錄下,能夠看到生成了一個activity_databinding-layout.xml
文件,這個文件名稱是在咱們原來的佈局名稱後加上了-layout。它的內容如上圖右側所示。在最外層的節點裏記錄了對應的佈局文件,而後經過定義Variables
節點,記錄了對應的數據類。在Targets
節點中,記錄了原佈局的tag
,及使用了DataBinding的控件的tag,而後經過Expression
節點,記錄對應的數據。
在app/build/intermediates/incremental/mergeDebugResources/stripped.dir/layout/
目錄下,能夠看到activity_databinding.xml
文件,這個文件就是咱們原來的文件名,不過裏面稍做了一些變更,增長了一些tag
,這些tag的值和前面的activity_databinding-layout.xml
記錄的是對應的。
咱們從DataBindingUtil.setContentView(this, R.layout.activity_databinding)
這個方法看起。
public static <T extends ViewDataBinding> T setContentView(@NonNull Activity activity, int layoutId) {
return setContentView(activity, layoutId, sDefaultComponent);
}
複製代碼
這個方法裏又調用了setContentView
方法
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);
}
複製代碼
這個方法裏調用了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
方法
static <T extends ViewDataBinding> T bind(DataBindingComponent bindingComponent, View root, int layoutId) {
return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);
}
複製代碼
這裏調用了sMapper
的getDataBinder
方法,sMapper其實就是自動生成的DataBinderMapperImpl
文件
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_ACTIVITYDATABINDING: {
if ("layout/activity_databinding_0".equals(tag)) {
return new ActivityDatabindingBindingImpl(component, view);
}
throw new IllegalArgumentException("The tag for activity_databinding is invalid. Received: " + tag);
}
}
}
return null;
}
複製代碼
在這裏調用了ActivityDatabindingBindingImpl
的構造方法
public ActivityDatabindingBindingImpl(@Nullable androidx.databinding.DataBindingComponent bindingComponent, @NonNull View root) {
this(bindingComponent, root, mapBindings(bindingComponent, root, 3, sIncludes, sViewsWithIds));
}
複製代碼
這裏調用了ViewDataBinding
類mapBindings
方法
protected static Object[] mapBindings(DataBindingComponent bindingComponent, View root, int numBindings, ViewDataBinding.IncludedLayouts includes, SparseIntArray viewsWithIds) {
Object[] bindings = new Object[numBindings];
mapBindings(bindingComponent, root, bindings, includes, viewsWithIds, true);
return bindings;
}
複製代碼
這裏調用mapBindings
方法
private static void mapBindings(DataBindingComponent bindingComponent, View view, Object[] bindings, ViewDataBinding.IncludedLayouts includes, SparseIntArray viewsWithIds, boolean isRoot) {
ViewDataBinding existingBinding = getBinding(view);
if (existingBinding == null) {
Object objTag = view.getTag();
String tag = objTag instanceof String ? (String)objTag : null;
boolean isBound = false;
int indexInIncludes;
int id;
int count;
if (isRoot && tag != null && tag.startsWith("layout")) {
id = tag.lastIndexOf(95);
if (id > 0 && isNumeric(tag, id + 1)) {
count = parseTagInt(tag, id + 1);
if (bindings[count] == null) {
bindings[count] = view;
}
indexInIncludes = includes == null ? -1 : count;
isBound = true;
} else {
indexInIncludes = -1;
}
} else if (tag != null && tag.startsWith("binding_")) {
id = parseTagInt(tag, BINDING_NUMBER_START);
if (bindings[id] == null) {
bindings[id] = view;
}
isBound = true;
indexInIncludes = includes == null ? -1 : id;
} else {
indexInIncludes = -1;
}
if (!isBound) {
id = view.getId();
if (id > 0 && viewsWithIds != null && (count = viewsWithIds.get(id, -1)) >= 0 && bindings[count] == null) {
bindings[count] = view;
}
}
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup)view;
count = viewGroup.getChildCount();
int minInclude = 0;
for(int i = 0; i < count; ++i) {
View child = viewGroup.getChildAt(i);
boolean isInclude = false;
if (indexInIncludes >= 0 && child.getTag() instanceof String) {
String childTag = (String)child.getTag();
if (childTag.endsWith("_0") && childTag.startsWith("layout") && childTag.indexOf(47) > 0) {
int includeIndex = findIncludeIndex(childTag, minInclude, includes, indexInIncludes);
if (includeIndex >= 0) {
isInclude = true;
minInclude = includeIndex + 1;
int index = includes.indexes[indexInIncludes][includeIndex];
int layoutId = includes.layoutIds[indexInIncludes][includeIndex];
int lastMatchingIndex = findLastMatching(viewGroup, i);
if (lastMatchingIndex == i) {
bindings[index] = DataBindingUtil.bind(bindingComponent, child, layoutId);
} else {
int includeCount = lastMatchingIndex - i + 1;
View[] included = new View[includeCount];
for(int j = 0; j < includeCount; ++j) {
included[j] = viewGroup.getChildAt(i + j);
}
bindings[index] = DataBindingUtil.bind(bindingComponent, included, layoutId);
i += includeCount - 1;
}
}
}
}
if (!isInclude) {
mapBindings(bindingComponent, child, bindings, includes, viewsWithIds, false);
}
}
}
}
}
複製代碼
這個方法其實就是解析前面的兩個xml文件,將綁定的控件保存起來。
DataBindingUtil.setContentView
方法執行完成後,就能夠獲取到對應的DataBinding對象。
來一張簡單的時序圖
binding.setUser對應的是ActivityDatabindingBindingImpl的setUser方法
public void setUser(@Nullable com.wangyz.jetpack.databinding.User User) {
updateRegistration(0, User);
this.mUser = User;
synchronized(this) {
mDirtyFlags |= 0x1L;
}
notifyPropertyChanged(BR.user);
super.requestRebind();
}
複製代碼
先來看updateRegistration
,這裏就是註冊過程。調用ViewDataBinding
的updateRegistration方法
protected boolean updateRegistration(int localFieldId, Observable observable) {
return updateRegistration(localFieldId, observable, CREATE_PROPERTY_LISTENER);
}
複製代碼
而後調用updateRegistration
方法
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;
}
複製代碼
調用registerTo
方法
protected void registerTo(int localFieldId, Object observable, CreateWeakListener listenerCreator) {
if (observable == null) {
return;
}
WeakListener listener = mLocalFieldObservers[localFieldId];
if (listener == null) {
listener = listenerCreator.create(this, localFieldId);
mLocalFieldObservers[localFieldId] = listener;
if (mLifecycleOwner != null) {
listener.setLifecycleOwner(mLifecycleOwner);
}
}
listener.setTarget(observable);
}
複製代碼
這個方法將傳進來的數據保存到WeakListener
中
執行完成updateRegistration
方法後,須要執行notifyPropertyChanged方法,通知更新,這個方法在BaseObservable裏
public void notifyPropertyChanged(int fieldId) {
synchronized (this) {
if (mCallbacks == null) {
return;
}
}
mCallbacks.notifyCallbacks(this, fieldId, null);
}
複製代碼
而後調用CallbackRegistry
的notifyCallbacks
方法
public synchronized void notifyCallbacks(T sender, int arg, A arg2) {
mNotificationLevel++;
notifyRecurse(sender, arg, arg2);
mNotificationLevel--;
if (mNotificationLevel == 0) {
if (mRemainderRemoved != null) {
for (int i = mRemainderRemoved.length - 1; i >= 0; i--) {
final long removedBits = mRemainderRemoved[i];
if (removedBits != 0) {
removeRemovedCallbacks((i + 1) * Long.SIZE, removedBits);
mRemainderRemoved[i] = 0;
}
}
}
if (mFirst64Removed != 0) {
removeRemovedCallbacks(0, mFirst64Removed);
mFirst64Removed = 0;
}
}
}
複製代碼
這裏調用了notifyRecurse
方法去遞歸通知
private void notifyRecurse(T sender, int arg, A arg2) {
final int callbackCount = mCallbacks.size();
final int remainderIndex = mRemainderRemoved == null ? -1 : mRemainderRemoved.length - 1;
// Now we've got all callbakcs that have no mRemainderRemoved value, so notify the
// others.
notifyRemainder(sender, arg, arg2, remainderIndex);
// notifyRemainder notifies all at maxIndex, so we'd normally start at maxIndex + 1
// However, we must also keep track of those in mFirst64Removed, so we add 2 instead:
final int startCallbackIndex = (remainderIndex + 2) * Long.SIZE;
// The remaining have no bit set
notifyCallbacks(sender, arg, arg2, startCallbackIndex, callbackCount, 0);
}
複製代碼
這個方法裏調用notifyCallbacks
方法
private void notifyCallbacks(T sender, int arg, A arg2, final int startIndex, final int endIndex, final long bits) {
long bitMask = 1;
for (int i = startIndex; i < endIndex; i++) {
if ((bits & bitMask) == 0) {
mNotifier.onNotifyCallback(mCallbacks.get(i), sender, arg, arg2);
}
bitMask <<= 1;
}
}
複製代碼
調用NotifierCallback
的onNotifyCallback
方法,它的具體回調在PropertyChangeRegistry
裏
private static final NotifierCallback<OnPropertyChangedCallback, Observable, Void> NOTIFIER_CALLBACK = new NotifierCallback<OnPropertyChangedCallback, Observable, Void>() {
public void onNotifyCallback(OnPropertyChangedCallback callback, Observable sender, int arg, Void notUsed) {
callback.onPropertyChanged(sender, arg);
}
};
複製代碼
而後回調Observable
的內部類OnPropertyChangedCallback
的onPropertyChanged
方法,而這個方法的實現是ViewDataBinding
的內部類WeakPropertyListener
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
方法
private void handleFieldChange(int mLocalFieldId, Object object, int fieldId) {
if (mInLiveDataRegisterObserver) {
// We're in LiveData registration, which always results in a field change
// that we can ignore. The value will be read immediately after anyway, so
// there is no need to be dirty.
return;
}
boolean result = onFieldChange(mLocalFieldId, object, fieldId);
if (result) {
requestRebind();
}
}
複製代碼
調用onFieldChange
方法,它的具體實現是ActivityDatabindingBindingImpl
protected boolean onFieldChange(int localFieldId, Object object, int fieldId) {
switch (localFieldId) {
case 0 :
return onChangeUser((com.wangyz.jetpack.databinding.User) object, fieldId);
}
return false;
}
複製代碼
調用onChangeUser
private boolean onChangeUser(com.wangyz.jetpack.databinding.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;
}
else if (fieldId == BR.age) {
synchronized(this) {
mDirtyFlags |= 0x4L;
}
return true;
}
return false;
}
複製代碼
在執行完onFieldChange
方法後,會再執行requestRebind
方法
protected void requestRebind() {
if (mContainingBinding != null) {
mContainingBinding.requestRebind();
} else {
final LifecycleOwner owner = this.mLifecycleOwner;
if (owner != null) {
Lifecycle.State state = owner.getLifecycle().getCurrentState();
if (!state.isAtLeast(Lifecycle.State.STARTED)) {
return; // wait until lifecycle owner is started
}
}
synchronized (this) {
if (mPendingRebind) {
return;
}
mPendingRebind = true;
}
if (USE_CHOREOGRAPHER) {
mChoreographer.postFrameCallback(mFrameCallback);
} else {
mUIThreadHandler.post(mRebindRunnable);
}
}
}
複製代碼
在這裏post
了一個mRebindRunnable
到主線程中,看下mRebindRunnable
private final Runnable mRebindRunnable = new Runnable() {
@Override
public void run() {
synchronized (this) {
mPendingRebind = false;
}
processReferenceQueue();
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
// Nested so that we don't get a lint warning in IntelliJ
if (!mRoot.isAttachedToWindow()) {
// Don't execute the pending bindings until the View
// is attached again.
mRoot.removeOnAttachStateChangeListener(ROOT_REATTACHED_LISTENER);
mRoot.addOnAttachStateChangeListener(ROOT_REATTACHED_LISTENER);
return;
}
}
executePendingBindings();
}
};
複製代碼
在這個方法裏執行了executePendingBindings
方法
public void executePendingBindings() {
if (mContainingBinding == null) {
executeBindingsInternal();
} else {
mContainingBinding.executePendingBindings();
}
}
複製代碼
而後執行executeBindingsInternal
方法
private void executeBindingsInternal() {
if (mIsExecutingPendingBindings) {
requestRebind();
return;
}
if (!hasPendingBindings()) {
return;
}
mIsExecutingPendingBindings = true;
mRebindHalted = false;
if (mRebindCallbacks != null) {
mRebindCallbacks.notifyCallbacks(this, REBIND, null);
// The onRebindListeners will change mPendingHalted
if (mRebindHalted) {
mRebindCallbacks.notifyCallbacks(this, HALTED, null);
}
}
if (!mRebindHalted) {
executeBindings();
if (mRebindCallbacks != null) {
mRebindCallbacks.notifyCallbacks(this, REBOUND, null);
}
}
mIsExecutingPendingBindings = false;
}
複製代碼
這個方法裏執行了executeBindings
方法,它在實現是ActivityDatabindingBindingImpl
protected void executeBindings() {
long dirtyFlags = 0;
synchronized(this) {
dirtyFlags = mDirtyFlags;
mDirtyFlags = 0;
}
java.lang.String userName = null;
int userAge = 0;
com.wangyz.jetpack.databinding.User user = mUser;
java.lang.String stringValueOfUserAge = null;
if ((dirtyFlags & 0xfL) != 0) {
if ((dirtyFlags & 0xbL) != 0) {
if (user != null) {
// read user.name
userName = user.getName();
}
}
if ((dirtyFlags & 0xdL) != 0) {
if (user != null) {
// read user.age
userAge = user.getAge();
}
// read String.valueOf(user.age)
stringValueOfUserAge = java.lang.String.valueOf(userAge);
}
}
// batch finished
if ((dirtyFlags & 0xbL) != 0) {
// api target 1
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.mboundView1, userName);
}
if ((dirtyFlags & 0xdL) != 0) {
// api target 1
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.mboundView2, stringValueOfUserAge);
}
}
複製代碼
能夠看到,是經過androidx.databinding.adapters.TextViewBindingAdapter.setText來實現的
public static void setText(TextView view, CharSequence text) {
final CharSequence oldText = view.getText();
if (text == oldText || (text == null && oldText.length() == 0)) {
return;
}
if (text instanceof Spanned) {
if (text.equals(oldText)) {
return; // No change in the spans, so don't set anything.
}
} else if (!haveContentsChanged(text, oldText)) {
return; // No content changes, so don't set anything.
}
view.setText(text);
}
複製代碼
這裏咱們界面就發生了變動。
來一張簡單的時序圖
public boolean setVariable(int variableId, @Nullable Object variable) {
boolean variableSet = true;
if (BR.user == variableId) {
setUser((com.wangyz.jetpack.databinding.User) variable);
}
else {
variableSet = false;
}
return variableSet;
}
複製代碼
最終仍是經過setUser來實現的。