目录

Android Butter Knife 初探

目录

Butter Knife 是 Android 项目常用的一个开源库,目的是简化繁复的 findViewByIdsetOnClickListener 编写。

使用之前先试用 Gradle 添加(在 app/build.gradle 文件中):

1
2
3
4
5
6
...
dependencies {
    ...
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}

版本号应参照官网说明进行设置

Butter Knife 借助 APT 进行代码处理,对有特定标注的声明和方法进行处理,注入正确的 View 对象和监听器。 比如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class ExampleActivity extends Activity {
  @BindView(R.id.title) TextView title;
  @BindView(R.id.subtitle) TextView subtitle;
  @BindView(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // Use fields...
  }
}

这样使用 @BindView(R.id.xxx) 的注解可以注入相应 id 的 View 对象,省去再 onCreate 方法里重复的输入大段的 findViewById

以及其他资源也使用 @BindXxx(R.xxx.xxx) 注入:

1
2
3
4
5
6
7
class ExampleActivity extends Activity {
  @BindString(R.string.title) String title;
  @BindDrawable(R.drawable.graphic) Drawable graphic;
  @BindColor(R.color.red) int red; // int or ColorStateList field
  @BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field
  // ...
}

还有按钮点击的监听器使用 @OnClick(R.id.xxx) 注入:

1
2
3
4
@OnClick(R.id.submit)
public void submit(View view) {
  // submit data to server...
}

另外,特别注意的是在 Intellij 或者 Android Studio 中还有相应的辅助插件 ButterKnifeZelezny,可以自动生产注解,更加简单方便。插件的 GitHub 地址为 https://github.com/avast/android-butterknife-zelezny,其中的安装和使用教程简介明白,此处不再赘述。