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編碼規(guī)范 -->
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 定義該View(布局)需要綁定的數據來源 -->
    <data>
        <variable
            name="user"
            type="com.yu.databinding.model.UserInfo" />
    </data>

    <!-- 布局常規(guī)編碼 -->
    <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)做了什么,怎么實現(xiàn)的雙向綁定?

二、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);跟我們常規(guī)設置的沒區(qū)別,然后用activity找到了decorView用于更新頁面,關于DecorView看這里,然后繼續(xù)跟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數組,繼續(xù)跟:

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

繼續(xù)跟sMapper.getDataBinder發(fā)現(xiàn)這是個抽象類,看看在哪里實現(xiàn)了(方法是按option+command+B):

尋找實現(xiàn)類

很顯然應該去我們自己的類里跟,那這里奇怪了,我們并沒有寫這個類,這個是Databinding里用APT技術自動生成的類:
APT生成文件目錄

APT生成的文件都在這里,APT在這里簡單介紹過,這里知道是自動生成文件的一種技術就行,跟進去這個getDataBinder方法,同樣是兩個實現(xiàn),一個單個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;
  }

這里發(fā)現(xiàn)了從view里取tag的操作,下面這個實現(xiàn)只是檢查了view是否有tag,上面這個實現(xiàn)中有個layout/activity_main_0,沒錯,就是上面自動生成的XML中的tag,然后返回了個ActivityMainBindingImpl的實現(xiàn),這個文件也是自動生成的,點這個類繼續(xù)追:

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

這里發(fā)現(xiàn)調用了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;
               ...
            }

           ...
    }

這里又發(fā)現(xiàn)一些熟悉的東西layout、binding_,正是剛才XML中View的Tag,看到這里我們得出這個函數是把剛才的XML文件解析出的控件放進一個數組中,然后繼續(xù)看上面那個重載函數,從數組中取出了這些控件,個這些控件取出的控件點一下看看,就是我們定義的一些控件:

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

然后調用了invalidateAll(),繼續(xù)跟這個函數:

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

繼續(xù)跟requestRebind()

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

這里的post(mRebindRunnable)跟下去會發(fā)現(xiàn)很多sendMessage的操作,這里就不貼了,
看看這個mRebindRunnable里做了什么,中間的過程不貼了,順序跟下來是這樣的:
executePendingBindings()->executeBindingsInternal()->executeBindings(),這個executeBindings是抽象的,需要看自己的實現(xiàn):

    @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()

這個代碼跟完之后,還有個地方需要注意的,就是這個類的靜態(tài)塊:

    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都會有一個監(jiān)聽View變化的,一旦有view變化,會調用mRebindRunnable.run(),mRebindRunnable上面已經跟過,是做刷新用的,也就是每個Activity都會有一個Runnable去做刷新工作。

代碼到這里看差不多了,有些沒貼到沒說到或者迷糊的地方進去點點,這里的代碼量并不大。
但是看代碼的過程也發(fā)現(xiàn)了一些問題,就是內存的開銷,其中主要有這么幾點:

  1. 有一個數組去存儲這些控件
  2. ActivityMainBindingImpl這個類對應有個Runnable負責刷新
  3. 還看到一行這樣的代碼mUIThreadHandler.post(mRebindRunnable),這個mUIThreadHandler也是一個Handler,Handler內部的Looper也會維持一個線程

這個ActivityMainBindingImpl是根據使用了Databinding的布局文件生成的,每一個是用了Databinding的布局都會生成這么一個文件,也可以理解問每一個Activity就會對應一個數組和兩個線程,數組的大小是該布局控件數量決定的。

隨著項目越來越大,使用Databinding的缺點也就越來越明顯:

  1. APT需要生成的文件也越來越多,編譯就會越來越慢
  2. 內存消耗越來越大

項目地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容