Android学习笔记---开源工具ButterKnife的使用

ButterKnife是一个Android的开源工具,是一个View的注入工具.他可以极大的简化我们的代码,帮我们省略大量的findViewById()setOnClickListener().而且它的使用非常简单.

ButterKnife的使用

ButterKnife是通过注解来完成对View对象的绑定,若对Java注解不了解,可以看一下我写的一篇博客:Java学习笔记—Annotation

  1. 依赖配置
    首先要使用ButterKnife我们需要在我们项目的app/build.gradle文件中添加依赖:
    在文件开始添加:
    1
    apply plugin: 'android-apt'

dependencies节点下添加

1
2
compile 'com.jakewharton:butterknife:8.0.1'
apt 'com.jakewharton:butterknife-compiler:8.0.1'

最后在项目根目录的build.gradle文件的dependencies节点下添加

1
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

  1. 基本使用

    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);
    }
    }

    通过@BindView()注解将控件ID与View对象绑定,最后使用ButterKnife.bind()进行注入.
    除了对View的绑定进行注入外,ButterKnife还能对Android中的其他资源进行注入:

    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
    // ...
    }

除此之外,还能对事件进行绑定:

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

ButterKnife的使用是非常简单明了的,从此再也不用使用烦人的findViewById了.ButterKnife的作用远远不止我上面所说到的,如果希望对此有跟加多的了解,可以查看ButterKnife官方网站和其GitHub上的源码.