
前言
在沒有使用DataBinding之前,我的項目都是使用ButterKnife,當然對于ButterKnife大家估計都熟悉的不要太熟悉了。本文我也就當自己的一個總結。

基本使用
基本使用我就直接貼相關的ButterKnife使用教程的文章鏈接:
從Github鏈接我們也可以看出有哪些基本的功能注解:
butterknife : android library model 提供android使用的API
butterknife-annotations: java-model,使用時的注解
butterknife-compiler: java-model,編譯時用到的注解的處理器
butterknife-gradle-plugin: 自定義的gradle插件,輔助生成有關代碼
butterknife-integration-test: 該項目的測試用例
butterknife-lint: 該項目的lint檢查
sample: demo
我們同時可以在butterknife-annotations里面看到基本的注解:

具體流程
我們從二個方面來看:

1.生成XXXX_ViewBinding.java文件:

public class AAA extends Activity{
@BindView(R.id.textView)
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aaa);
}
}
我們寫一個最簡單的Demo,就綁定了一個TextView。(這時候并沒有ButterKnife.bind(this)代碼) 我們按下Android Studio的編譯按鈕,當編譯完成后,我們查看文件:

我們可以發(fā)現(xiàn)在編譯后多了一個AAA_ViewBinding.java文件
public class AAA_ViewBinding implements Unbinder {
private AAA target;//可以看到這里的target是AAA這個Activity的實例對象。
@UiThread
public AAA_ViewBinding(AAA target) {
//先調(diào)用這個一個參數(shù)的構造函數(shù),然后調(diào)用下面的二個參數(shù)的構造函數(shù)
this(target, target.getWindow().getDecorView());
}
@UiThread
public AAA_ViewBinding(AAA target, View source) {
//這里的target就是AAA這個Activity的實例,
//source就是上面的單個構造函數(shù)生成的AAA這個Activity的DecorView
/*(ps:一般我們在Activity中setContentView(R.layout.XXX);
就是在我們寫的布局設置到了DecorView里面。)
*/
this.target = target;
//target.tv就是我們寫的AAA里面定義的TextView tv;
//通過Utils.findRequiredViewAsType進行tv的實例化,
/*(ps:因為這里是要taget.tv,所以如果我們在AAA里面的TextView用的private就會有問題了
當然實際private的判斷是在生成AAA_ViewBinding.java這個文件的時候就會去判斷
)*/
target.tv = Utils.findRequiredViewAsType(source, R.id.textView, "field 'tv'", TextView.class);
}
@Override
@CallSuper
public void unbind() {
AAA target = this.target;
if (target == null) throw new IllegalStateException("Bindings already cleared.");
this.target = null;
target.tv = null;
}
}
我們可以具體看下Utils.findRequiredViewAsType方法:
public static <T> T findRequiredViewAsType(View source, @IdRes int id, String who,
Class<T> cls) {
View view = findRequiredView(source, id, who);
return castView(view, id, who, cls);
}
public static View findRequiredView(View source, @IdRes int id, String who) {
View view = source.findViewById(id);
if (view != null) {
return view;
}
String name = getResourceEntryName(source, id);
throw new IllegalStateException("Required view '"
+ name
+ "' with ID "
+ id
+ " for "
+ who
+ " was not found. If this view is optional add '@Nullable' (fields) or '@Optional'"
+ " (methods) annotation.");
}
可以看到最后是View view = source.findViewById(id);來幫我們TextView賦值。
可能大家會說。那這個AAA_ViewBinding.java文件到底是怎么生成的,為什么編譯下后,會生成這么個文件,為什么這個文件里面相關代碼也會有等。(初步可以這么理解,就是遍歷了我們在AAA.java中寫的注解,然后按照相應模板生成一個java文件。)
詳細的生成AAA_ViewBinding.java文件可以看以下鏈接:
2.實例化XXX_ViewBinding.java:

我們在上面的例子中可以看到,在生成的AAA_ViewBinding.java中有了對我們的TextView進行賦值。
那么現(xiàn)在的問題就是變成了實例化
AAA_ViewBinding.java,然后運行相應的這個TextView賦值的相關代碼.
這時候就需要執(zhí)行ButterKnife.bind(this);(ps:因為我們這個例子是在Activity中)。我們來看ButterKnife.bind(this)到底執(zhí)行了什么:
ButterKnife -- > bind:
@NonNull @UiThread
public static Unbinder bind(@NonNull Activity target) {
//target是我們傳入的this,也就是AAA這個Activity的實例
//獲取到AAA的DecorView實例化對象sourceView
View sourceView = target.getWindow().getDecorView();
//調(diào)用createBinding方法
return createBinding(target, sourceView);
}
createBinding:
private static Unbinder createBinding(@NonNull Object target, @NonNull View source) {
//1.獲取AAA的Class
Class<?> targetClass = target.getClass();
if (debug) Log.d(TAG, "Looking up binding for " + targetClass.getName());
//2.通過findBindingConstructorForClass獲得構造器
Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);
if (constructor == null) {
return Unbinder.EMPTY;
}
//noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
try {
//3. 通過構造器實例化
return constructor.newInstance(target, source);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to invoke " + constructor, e);
} catch (InstantiationException e) {
throw new RuntimeException("Unable to invoke " + constructor, e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException("Unable to create binding instance.", cause);
}
}
我們發(fā)現(xiàn)主要是第二步,獲取構造器,所以我們來看下findBindingConstructorForClass方法:
@Nullable @CheckResult @UiThread
private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
if (bindingCtor != null) {
if (debug) Log.d(TAG, "HIT: Cached in binding map.");
return bindingCtor;
}
String clsName = cls.getName();
if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search.");
return null;
}
try {
//加載了(clsName + "_ViewBinding")的類,也就是AAA_ViewBinding的Class對象,
//然后在用這個AAA_ViewBinding的Class對象獲取構造器。
Class<?> bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding");
//noinspection unchecked
bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class);
if (debug) Log.d(TAG, "HIT: Loaded binding class and constructor.");
} catch (ClassNotFoundException e) {
if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName());
bindingCtor = findBindingConstructorForClass(cls.getSuperclass());
} catch (NoSuchMethodException e) {
throw new RuntimeException("Unable to find binding constructor for " + clsName, e);
}
BINDINGS.put(cls, bindingCtor);
return bindingCtor;
}
所以當執(zhí)行了ButterKnife最后就是通過構造函數(shù)獲取了AAA_ViewBinding的實例,而在AAA_ViewBinding.java的構造函數(shù)中對TextView進行了賦值。
結尾
如果哪里有問題,歡迎大家留言提出。我可以及時改正,(▽)