ButterKnife
2018-9-6 10:45 - QG2017移动组 - 张艺隽
ButterKnife是JakeWharton大神出品的用于View的注入框架。提供注解来简单快捷地完成View的绑定、点击事件的分离等。
- 来自官方的说明:
Field and method binding for Android views which uses annotation processing to generate boilerplate code for you.
- Eliminate findViewById calls by using @BindView on fields.
- Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.
- Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.
- Eliminate resource lookups by using resource annotations on fields.
Remember: A butter knife is like a dagger only infinitely less sharp.
非常有意思的一句话,这里的匕首指的是Android的另一个主流的依赖注入框架Dagger。
0. 参考资料
1. 开始使用
- 导入依赖:
dependencies {
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}
如果使用Kotlin,则将**annotationProcessor**替换为**kapt** 2. 如果不需要在library中使用ButterKnife,则**直接跳过以下步骤。** - 修改buildscript:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
}
}
- 需要gradle降级
classpath 'com.android.tools.build:gradle:3.0.1'
- 在module上方加入:
apply plugin: 'com.jakewharton.butterknife'
- 确保R全部替换为R2
class ExampleActivity extends Activity {
@BindView(R2.id.user) EditText username;
@BindView(R2.id.pass) EditText password;
}
2. zelezny插件
- 安装:zelezny是编译器层面的插件,用于辅助ButterKnife,提供快捷方法来绑定控件。在AS的Setting中找到Plugins,然后搜索插件:zelezny,安装后重启AS。
- 使用:
setContentView(R.layout.acty_login)
将鼠标移到acty_login上,右键选择Generate(或Alt+Insert),点击选项Generate ButterKnife Injecttions即可。
3. @BindView
@BindView注解是ButterKnife中最基本的用法,先观看源码:
@Retention(CLASS) @Target(FIELD)
public @interface BindView {
/** View ID to which the field will be bound. */
@IdRes int value();
}
@IdRes注解指定@BindView的参数为一个控件资源。
Java
- 在Activity的setContentView后使用ButterKnife.bind(this)
- 在方法外部使用注解@BindView()绑定控件。绑定的控件不能被private或static修饰。