一、先看看ButterKnife的简单使用
1. 导入ButterKnife
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
2. MainActivity(绑定当前view)
@BindView(R.id.btn)
Button mButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mButton.setText("test");
}
@OnClick(R.id.btn)
public void btnOnclick() {
Intent intent = new Intent(MainActivity.this, Main3Activity.class
);
startActivity(intent);
}
二、源码分析(ButterKnife.java)
1. 看看bind做了什么事件,其实就是返回一个Unbinder对象。这个对象是一个(clsName + "_ViewBinding")的类,实现Unbinder。(这里使用的反射)
@NonNull @UiThread
public static Unbinder bind(@NonNull Object target, @NonNull Dialog source) {
View sourceView = source.getWindow().getDecorView();
return createBinding(target, sourceView);
}
private static Unbinder createBinding(@NonNull Object target, @NonNull View source) {
Class<?> targetClass = target.getClass();
if (debug) Log.d(TAG, "Looking up binding for " + targetClass.getName());
Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);
if (constructor == null) {
return Unbinder.EMPTY;
}
//反射创建Unbinder
return constructor.newInstance(target, source);
}
private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
// 缓存的LinkedHashMap 查找当前的activity是否缓存
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 {
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);
}
// ViewBinder的子类的类名(MainActivity$$ViewBinder),然后通过反射的形式创建(MainActivity$$ViewBinder)的实例,并存入缓存
BINDINGS.put(cls, bindingCtor);
return bindingCtor;
}
2. 看看Unbinder是什么
public interface Unbinder {
@UiThread void unbind();
Unbinder EMPTY = new Unbinder() {
@Override public void unbind() { }
};
3. 看看生成的MainActivity_ViewBinding.java是什么样子的(在build/generated/source/apt文件夹)
public class MainActivity_ViewBinding implements Unbinder {
private MainActivity target;
private View view2131165218;
@UiThread
public MainActivity_ViewBinding(MainActivity target) {
this(target, target.getWindow().getDecorView());
}
@UiThread
public MainActivity_ViewBinding(final MainActivity target, View source) {
this.target = target;
View view;
// 主要就是 View view = source.findViewById(id);
view = Utils.findRequiredView(source, R.id.btn, "field 'mButton' and method 'btnOnclick'");
target.mButton = Utils.castView(view, R.id.btn, "field 'mButton'", Button.class);
view2131165218 = view;
// 设置点击事件
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.btnOnclick();
}
});
}
@Override
@CallSuper
public void unbind() {
MainActivity target = this.target;
if (target == null) throw new IllegalStateException("Bindings already cleared.");
this.target = null;
target.mButton = null;
view2131165218.setOnClickListener(null);
view2131165218 = null;
}
}
4. 这个类是怎么生成的,使用了APT(编译时解析技术),对于注解在编译时候解析是通过我们自定义一个继承AbstractProcessor的类来完成的。所以我们找找ButterKnife的源码,在butterknife-compile (ButterKnifeProcessor.java)
@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;
}
5. 可以看出这个类主要就是做了两件事,首先是通过findAndParseTargets方法找出该类里所有注解,然后通过binding.brewJava方法将这些注解进行处理。
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 {
// 创建一个BindingSet抽象类,然后将我们注解信息处理后保存在里面
parseBindView(element, builderMap, erasedTargetNames);
} catch (Exception e) {
logParsingError(element, BindView.class, e);
}
}
// .........
return bindingMap;
}
6. 通过binding.brewJava方法将这些注解进行处理。(BindingSet.java)通过JavaFile创建出新的类。而这个新生成的className+_ViewBinding“”类,我们可以在ButterKnife.bind时候获取到它,然后就通过这个类里的方法,实现我们控件和监听方法的绑定了。
JavaFile brewJava(int sdk, boolean debuggable) {
TypeSpec bindingConfiguration = createType(sdk, debuggable);
//采用了JavaPoet,一个非常强大的代码生成工具。根据我们的注解内容,通过TypeSpec类和MethodSpec类构造出对应的方法,然后根据之前创建BindingSet抽象类时候创建的新类名。
return JavaFile.builder(bindingClassName.packageName(), bindingConfiguration)
.addFileComment("Generated code from Butter Knife. Do not modify!")
.build();
}
三、总结
使用编译时注解,在编译时期自动生成Unbinder(APT),这个对象自动生成了我们需要的动画、监听事件等等。
在我们的Activity中使用Bind进行绑定,我们就执行了自动生成的代码。而且返回一个Unbinder。
ButterKnife不能将控件和方法设置为private或者static,是因为在className_ViewBinder类会直接调用该控件和方法进行赋值。
编译时注解+APT
编译时注解:@Retention(CLASS)。
APT(Annotation Processing Tool)编译时解析技术。