项目地址
GitHub地址:https://github.com/JakeWharton/butterknife
简介
ButterKnife这个开源库可以让我们从大量的findViewById和setOnClickListener中解放出来,其对性能的影响微乎其微(其自定义注解的实现都是限定为RetentionPolicy.CLASS,也就是编译出.class文件为止有效,在运行时不额外消耗性能,其实通过java注解自动生成java代码的形式来完成工作),但也有一个明显的缺点,那就是代码的可读性差些,凡事有利有弊,我们需要做到有的放矢。
应用
Activity Binding
|
|
调用注解bind生成的代码是可见的并且能够调试,上面的示例通过Bind注解生成的代码相当于下面的代码:
|
|
RESOURCE BINDING
Bind pre-defined resources with @BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString, which binds an R.bool ID (or your specified type) to its corresponding field.
|
|
NON-ACTIVITY BINDING
|
|
ADAPTER BINDING
|
|
LIST OR ARRAY BINDING
|
|
LISTENER BINDING
|
|
|
|
|
|
|
|
|
|
BINDING RESET
相对于Activity,Fragment有与之不同的视图声明周期。当早onCreateView中bind一个Fragment的时候,需要在OnDestroyView中将views设置为null。Butter Knife 通过一个ButterKnife.Unbinder接口来自动完成这个过程. Simply bind an unbinder with @Unbinder to the fragment.
|
|
OPTIONAL BINDINGS
默认情况下,@Bind和绑定的目标是必须存在的,如果目标View不存在将会抛出异常。
为了避免这样情况并且创建一个可选的绑定目标,给变量增加@Nullable注解或者给方法增加 @Optional注解.
Note: Any annotation named @Nullable or can be used for fields. It is encouraged to use the @Nullable annotation from Android’s “support-annotations” library.
|
|
|
|
MULTI-METHOD LISTENERS
|
|
|
|
BONUS
Also included are findById methods which simplify code that still has to find views on a View, Activity, or Dialog. It uses generics to infer the return type and automatically performs the cast.
|
|