目的:分析ButterKnife如何進(jìn)行view與onClick事件的綁定
原理分析
通過觀察BindView注解發(fā)現(xiàn)阻塑,該注解是存在于編譯器的:
@Retention(CLASS) @Target(FIELD)
public @interface BindView {
/** View ID to which the field will be bound. */
@IdRes int value();
}
那么猜想肯定需要通過注解處理器來處理該注解注釋的字段或方法。
找到引用:
kapt "com.jakewharton:butterknife-compiler:8.8.1"
找到注解編譯器源碼:ButterKnifeProcessor extends AbstractProcessor{}
通過重寫getSupportedAnnotationTypes
方法來獲取支持的注解類型:
@Override public Set<String> getSupportedAnnotationTypes() {
Set<String> types = new LinkedHashSet<>();
for (Class<? extends Annotation> annotation : getSupportedAnnotations()) {
types.add(annotation.getCanonicalName());
}
return types;
}
private Set<Class<? extends Annotation>> getSupportedAnnotations() {
Set<Class<? extends Annotation>> annotations = new LinkedHashSet<>();
annotations.add(BindAnim.class);
annotations.add(BindArray.class);
annotations.add(BindBitmap.class);
annotations.add(BindBool.class);
annotations.add(BindColor.class);
annotations.add(BindDimen.class);
annotations.add(BindDrawable.class);
annotations.add(BindFloat.class);
annotations.add(BindFont.class);
annotations.add(BindInt.class);
annotations.add(BindString.class);
annotations.add(BindView.class);
annotations.add(BindViews.class);
annotations.addAll(LISTENERS);
return annotations;
}
在獲取到所有的上述類型后,會(huì)進(jìn)入process
方法進(jìn)行處理:
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);
for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
TypeElement typeElement = entry.getKey();
BindingSet binding = entry.getValue();
JavaFile javaFile = binding.brewJava(sdk, debuggable);
try {
javaFile.writeTo(filer);
} catch (IOException e) {
error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
}
}
return false;
}
該方法異常簡短贩毕,主要是做了很多的封裝刺彩,其中BindingSet類就是一個(gè)封裝了將要生成的中間類的代碼的類。在該類中躯砰,會(huì)通過解析的注解的屬性來將對應(yīng)的語句添加到BindingSet.Builder中每币,也可通過其中的addMethod向中間類中添加方法。
因此findAndParseTargets
方法的主要工作就是解析各個(gè)注解信息并生成對應(yīng)的語句放入BindingSet中琢歇。在所有的解析完畢后兰怠,會(huì)輪詢該Map集合,然后通過JavaFile來生成中間類李茫。
下邊詳細(xì)看一下findAndParseTargets
方法:
private Map<TypeElement, BindingSet> findAndParseTargets(RoundEnvironment env) {
Map<TypeElement, BindingSet.Builder> builderMap = new LinkedHashMap<>();
Set<TypeElement> erasedTargetNames = new LinkedHashSet<>();
// Process each @BindView element.
for (Element element : env.getElementsAnnotatedWith(BindView.class)) {
// we don't SuperficialValidation.validateElement(element)
// so that an unresolved View type can be generated by later processing rounds
try {
parseBindView(element, builderMap, erasedTargetNames);
} catch (Exception e) {
logParsingError(element, BindView.class, e);
}
}
// Process each annotation that corresponds to a listener.
for (Class<? extends Annotation> listener : LISTENERS) {
findAndParseListener(env, listener, builderMap, erasedTargetNames);
}
// Associate superclass binders with their subclass binders. This is a queue-based tree walk
// which starts at the roots (superclasses) and walks to the leafs (subclasses).
Deque<Map.Entry<TypeElement, BindingSet.Builder>> entries =
new ArrayDeque<>(builderMap.entrySet());
Map<TypeElement, BindingSet> bindingMap = new LinkedHashMap<>();
while (!entries.isEmpty()) {
Map.Entry<TypeElement, BindingSet.Builder> entry = entries.removeFirst();
TypeElement type = entry.getKey();
BindingSet.Builder builder = entry.getValue();
TypeElement parentType = findParentType(type, erasedTargetNames);
if (parentType == null) {
bindingMap.put(type, builder.build());
} else {
BindingSet parentBinding = bindingMap.get(parentType);
if (parentBinding != null) {
builder.setParent(parentBinding);
bindingMap.put(type, builder.build());
} else {
// Has a superclass binding but we haven't built it yet. Re-enqueue for later.
entries.addLast(entry);
}
}
}
return bindingMap;
}
在該方法中揭保,會(huì)處理收集每種注解類型的信息,上邊只粘出了BindView和OnClick的片段魄宏。以BindView為例:
private void parseBindView(Element element, Map<TypeElement, BindingSet.Builder> builderMap,
Set<TypeElement> erasedTargetNames) {
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
// Start by verifying common generated code restrictions.
boolean hasError = isInaccessibleViaGeneratedCode(BindView.class, "fields", element)
|| isBindingInWrongPackage(BindView.class, element);
// Verify that the target type extends from View.
TypeMirror elementType = element.asType();
if (elementType.getKind() == TypeKind.TYPEVAR) {
TypeVariable typeVariable = (TypeVariable) elementType;
elementType = typeVariable.getUpperBound();
}
Name qualifiedName = enclosingElement.getQualifiedName();
Name simpleName = element.getSimpleName();
// Assemble information on the field.
int id = element.getAnnotation(BindView.class).value();
BindingSet.Builder builder = builderMap.get(enclosingElement);
Id resourceId = elementToId(element, BindView.class, id);
if (builder != null) {
String existingBindingName = builder.findExistingBindingName(resourceId);
} else {
builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
}
String name = simpleName.toString();
TypeName type = TypeName.get(elementType);
boolean required = isFieldRequired(element);
builder.addField(resourceId, new FieldViewBinding(name, type, required));
// Add the type-erased version to the valid binding targets set.
erasedTargetNames.add(enclosingElement);
}
會(huì)收集修飾字段的修飾符秸侣,字段名稱,字段類型等信息娜庇,然后通過builder.addField將該字段添加到BindingSet.Builder中塔次。
在收集到所有的類型后,最終會(huì)通過:
JavaFile javaFile = binding.brewJava(sdk, debuggable);
javaFile.writeTo(filer);
生成中間類名秀。binding.brewJava方法:
JavaFile brewJava(int sdk, boolean debuggable) {
TypeSpec bindingConfiguration = createType(sdk, debuggable);
return JavaFile.builder(bindingClassName.packageName(), bindingConfiguration)
.addFileComment("Generated code from Butter Knife. Do not modify!")
.build();
}
就是直接調(diào)用JavaFile來創(chuàng)建類励负。而createType就是通過在解析時(shí)添加到Binding.Builder中的語句字段來生成類的代碼,比如包名類名等匕得。
最終生成的中間類代碼如下:
// Generated code from Butter Knife. Do not modify!
package com.jf.jlfund.view.activity;
import butterknife.internal.DebouncingOnClickListener;
import butterknife.internal.Utils;
import com.jf.jlfund.R;
public class FundSaleOutActivity_ViewBinding implements Unbinder {
private FundSaleOutActivity target;
private View view2131231970;
@UiThread
public FundSaleOutActivity_ViewBinding(FundSaleOutActivity target) {
this(target, target.getWindow().getDecorView());
}
@UiThread
public FundSaleOutActivity_ViewBinding(final FundSaleOutActivity target, View source) {
this.target = target;
View view;
target.rootView = Utils.findRequiredViewAsType(source, R.id.rl_fundSaleOut_rootView, "field 'rootView'", RelativeLayout.class);
target.commonTitleBar = Utils.findRequiredViewAsType(source, R.id.commonTitleBar_fundSaleOut, "field 'commonTitleBar'", CommonTitleBar.class);
target.etAmount = Utils.findRequiredViewAsType(source, R.id.et_fundSaleOut, "field 'etAmount'", EditText.class);
view = Utils.findRequiredView(source, R.id.tv_fundSaleOut_saleAll, "field 'tvSaleAll' and method 'onClick'");
target.tvSaleAll = Utils.castView(view, R.id.tv_fundSaleOut_saleAll, "field 'tvSaleAll'", TextView.class);
view2131231970 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.onClick(p0);
}
});
}
@Override
@CallSuper
public void unbind() {
FundSaleOutActivity target = this.target;
if (target == null) throw new IllegalStateException("Bindings already cleared.");
this.target = null;
target.rootView = null;
target.commonTitleBar = null;
target.etAmount = null;
target.tvSaleAll = null;
view2131231970.setOnClickListener(null);
view2131231970 = null;
}
}
其中继榆,Utils.findRequiredViewAsType
的作用就是source.findViewById并將查找的view轉(zhuǎn)換成具體的類型。
以上的工作都發(fā)生在編譯器汁掠,那么如何在運(yùn)行期來進(jìn)行view的綁定呢略吨?
回想每次在Activity中使用都要事先進(jìn)行:
Unbinder unbinder = ButterKnife.bind(this);
bind方法:
@NonNull @UiThread
public static Unbinder bind(@NonNull Activity target) {
View sourceView = target.getWindow().getDecorView();
return createBinding(target, sourceView);
}
看語句是先獲取該Activity的DecorView,然后作為rootView進(jìn)行控件的綁定:
private static Unbinder createBinding(@NonNull Object target, @NonNull View source) {
Class<?> targetClass = target.getClass();
Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);
if (constructor == null) {
return Unbinder.EMPTY;
}
//noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
try {
return constructor.newInstance(target, source);
} catch (Exception e) {
//...
}
}
@Nullable @CheckResult @UiThread
private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
if (bindingCtor != null) {
return bindingCtor;
}
String clsName = cls.getName();
if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
return null;
}
try {
Class<?> bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding");
//noinspection unchecked
bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class);
} catch (ClassNotFoundException e) {}
BINDINGS.put(cls, bindingCtor);
return bindingCtor;
}
方法說明:
- 根據(jù)傳入的target來獲取對應(yīng)的在編譯器生成的target_ViewBinding類考阱。
- 獲取該類的構(gòu)造函數(shù)
- 通過傳入的參數(shù)執(zhí)行該類的構(gòu)造函數(shù)
上邊方法執(zhí)行完畢后翠忠,在編譯期生成的類就會(huì)被執(zhí)行在Activity的onCreate方法中。在回顧一下生成的類的代碼片段:
target.rootView = Utils.findRequiredViewAsType(source, R.id.rl_fundSaleOut_rootView, "field 'rootView'", RelativeLayout.class);
target.commonTitleBar = Utils.findRequiredViewAsType(source, R.id.commonTitleBar_fundSaleOut, "field 'commonTitleBar'", CommonTitleBar.class);
其中乞榨,findRequiredViewAsType
就是調(diào)用source.findViewById然后轉(zhuǎn)化成指定的類型秽之。而這個(gè)source就是我們傳入的DecorView当娱。
至此,view的綁定也就完成了考榨。事件的綁定也類似跨细。還有要記得,在Activity的onDestory中要調(diào)用:
unbinder.unbind();
該操作會(huì)把注解生成的view都給置空河质。
總結(jié)
- 通過注解處理器生成對應(yīng)的中間類**_ViewBinding冀惭,并將findViewById與事件點(diǎn)擊等操作寫入該類的構(gòu)造函數(shù)中。
- 在運(yùn)行期掀鹅,通過在Activity的onCreate方法中bind(this)來獲取該中間構(gòu)造函數(shù)散休,并通過反射構(gòu)造函數(shù)來實(shí)現(xiàn)view的綁定。