如何使用
添加依赖
implementation "com.jakewharton:butterknife:$butterKnifeVersion"
annotationProcessor "com.jakewharton:butterknife-compiler:$butterKnifeVersion"
在Activity中使用
声明Unbinder对象为局部变量
private Unbinder mUnbinder;
在Activity的onCreate生命周期中初始化mUnbinder
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......
setContentView(layoutResId);
......
mUnbinder=ButterKnife.bind(this);
......
}
用@BindView注解绑定view_id给你对应的view
@BindView(R.id.tv_date)
TextView tvDate;
当你view较多的时候需要你多次编写类似的代码,比较耗时,此时可以使用Android ButterKnife Zelezny插件。
如何添加插件?
添加插件
点击File打开菜单
点击File打开菜单
点击
Settings...打开设置页面
点击Settings...打开设置页面
点击
Plugins打开插件设置页面,选择Marketplace标签页
点击Plugins打开插件设置页面,选择Marketplace标签页
在搜索栏中输入
ButterKnife后,按回车确认,点击第一个插件下的INSTALL安装,安装完成后重启AndroidStudio
在搜索栏中输入ButterKnife后,按回车确认
使用插件
重启完成后打开你需要使用@BindView的Activity页面,在布局文件的id上单击右键,然后选择Generate...菜单
单击右键.jpg
在弹出的菜单中选择
Generate Butterknife Injections
选择最下方Generate Butterknife Injections
在之后的菜单中,勾选你需要在
Activity中创建的view,然后点击CONFIRM,就会自动生成对应的@BindView代码
勾选菜单生成对应代码
除了这些代码,还会额外在
onDestory方法中生成mUnbinder的解绑代码,是我们使用ButterKnife必要的代码
if (mUnbinder != null) {
mUnbinder.unbind();
}
以上就是在Activity中使用时的简单步骤
学习源码
查看学习Unbinder对象源码
import android.support.annotation.UiThread;
/** An unbinder contract that will unbind views when called. */
public interface Unbinder {
@UiThread void unbind();
Unbinder EMPTY = new Unbinder() {
@Override public void unbind() { }
};
}
其中包含了一个在UiThread中执行的unbind()方法,以及一个初始化好的EMPTY的Unbinder实例。
接下来查看学习ButterKnife.bind(this)的bind方法。
@NonNull @UiThread
public static Unbinder bind(@NonNull Activity target) {
View sourceView = target.getWindow().getDecorView();
return createBinding(target, sourceView);
}
这段代码获取了Activity的顶层视图,并作为参数传入了createBinding方法中,我们继续查看该方法
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;
}
//noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
try {
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);
}
}
这个方法再第四行代码中通过findBindingConstructorForClass(targetClass)方法获取到一个Constructor<? extends Unbinder>实例,余下的都是一些异常处理,那么我们就需要继续深入findBindingConstructorForClass(targetClass)一探究竟。
@Nullable @CheckResult @UiThread
private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
//BINDINGS
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);
}
BINDINGS.put(cls, bindingCtor);
return bindingCtor;
}
这里是实例化BINDINGS的代码,它是一个LinkedHashMap,用来缓存已经匹配到过的bindingCtor以节省开销。
可以看到上面的代码中倒数第二行,将匹配到的bindingCtor放入了BINDINGS中。
@VisibleForTesting
static final Map<Class<?>, Constructor<? extends Unbinder>> BINDINGS = new LinkedHashMap<>();
那么对我们来说有意义的代码就是try catch代码块中的内容了
Class<?> bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding");
//noinspection unchecked
bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class);
clsName是你传进来的Activity的名字,以我传入的为例与后面的拼接之后就是MainActivity_ViewBinding。我们全局搜索一下这个类名。
MainActivity_ViewBinding
这是我们编译代码之后生成的辅助文件。那么
findBindingConstructorForClass这个方法返回的就是通过反射得到的MainActivity_ViewBinding的构造方法。然后在createBinding方法中使用constructor.newInstance(target, source)得到了MainActivity_viewBinding的实例。至此,我们已经了解了
ButterKnife.bind(this)这个方法所做的工作。
接下来我们仔细查看这个生成的类帮我们做了什么。
target.vStatusBg = Utils.findRequiredView(source, R.id.v_status_bg, "field 'vStatusBg'");
target.tvDate = Utils.findRequiredViewAsType(source, R.id.tv_date, "field 'tvDate'", TextView.class);
target.tvMenuBuyCarService = Utils.castView(view, R.id.tv_menu_buy_car_service, "field 'tvMenuBuyCarService'", TextView.class);
我们查看MainActivity_ViewBinding类源码之后,看到,给对应的view赋值的方法有这三个。接下来我们继续查看这三个方法。
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.");
}
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 <T> T castView(View view, @IdRes int id, String who, Class<T> cls) {
try {
return cls.cast(view);
} catch (ClassCastException e) {
String name = getResourceEntryName(view, id);
throw new IllegalStateException("View '"
+ name
+ "' with ID "
+ id
+ " for "
+ who
+ " was of the wrong type. See cause for more info.", e);
}
}
我们可以看到最终还是通过findViewById给view赋值
到这里我们将简单的BindView的流程走完了,我们发现最重要的步骤其实应该是MainActivity_ViewBinding这个类的生成,它代替我们做了一系列findViewById的工作。
那我们会有一个疑问MainActivity_ViewBinding这个类是怎么生成的呢?
我们打开这个文件查看路径
Mainactivity_ViewBinding路径
当看到
apt时,我们搜一下apt是什么:APT(Annotation Processing Tool)即注解处理器,是一种处理注解的工具,确切的说它是javac的一个工具,它用来在编译时扫描和处理注解。注解处理器以Java代码(或者编译过的字节码)作为输入,生成.java文件作为输出。简单来说就是在编译期,通过注解生成
.java文件。
我们在添加ButterKnife依赖的时候还添加了这样一行代码annotationProcessor "com.jakewharton:butterknife-compiler:$rootProject.butterKnifeVersion"
接下来我们通过github下载得到butterknife的源码。
Butterknife源码
我们看到了我们所引用的butterknife-compiler项目,我们在下一篇来一探究竟。











网友评论