ButterKnife8的配置及使用

前言

从最初接触的 ButterKnife 5.0 到后来的 ButterKnife 7.0 大改动,再到如今的 ButterKnife 8.4,ButterKnife也在不断的进步,相对于 ButterKnife 7.0 最新的 ButterKnife 8.4 也有不小的改进,这样本文就重点来介绍一下8.4 的使用。

ButterKnife 的添加依赖

ButterKnife 8.4 在编译方面改用 annotationProcessor(编译时注解),这样就需要我们手动添加编译注解器。

  1. 首先,在Project的build.grade 中如图添加:
  2. 接下来,在app的build.gradle中添加声明,并引入依赖。

ButterKnife 的使用

ButterKnife 使用形式并没有打的改动,相对于Butterknife 7.0部分注解的名称有做修改。

首先说一下不论是哪个版本的ButterKnife 都需要注意的几个点:

  • ButterKnife.bind(this); 的使用一定是在setContentView()之后的;
  • 不管注解的是对象还是函数方法都不能用private 或者 static 修饰,否则会报错
  1. Activity中 绑定view
    使用 @BindView 加上一个ID的形式 来注解,即可自动的映射出布局中的相对应的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);
    // TODO Use fields...
    }
    }
  2. 资源绑定
    使用@BindBool,@BindColor,@BindDimen,@BindDrawable,@BindInt,@BindString绑定预定义的资源,通过以下形式绑定到其相应的字段。

    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
    // ...
    }
  3. 非Activity绑定
    还可以通过提供自己的根视图对任意对象执行绑定(以下以Fragment为例)。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class FancyFragment extends Fragment {
    @BindView(R.id.button1) Button button1;
    @BindView(R.id.button2) Button button2;
    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    ButterKnife.bind(this, view);
    // TODO Use fields...
    return view;
    }
    }

同样这种形式也可以应用在Adapter 中,简化视图的持有形式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class MyAdapter extends BaseAdapter {
@Override public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view != null) {
holder = (ViewHolder) view.getTag();
} else {
view = inflater.inflate(R.layout.whatever, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
}
holder.name.setText("John Doe");
// etc...
return view;
}
static class ViewHolder {
@BindView(R.id.title) TextView name;
@BindView(R.id.job_title) TextView jobTitle;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}

  1. 多View绑定

    • 将多个View 绑定到一个List 中 或者 数组也可以

      1
      2
      @BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
      List<EditText> nameViews;
    • apply方法,一次性对列表中的所有View执行操作。
      先来看一下apply方法都提供了那些重载:

      不仅仅有对列表或数组的批量操作,还有对单个视图的操作。
      下面看一下具体使用:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      ButterKnife.apply(nameViews, DISABLE);
      ButterKnife.apply(nameViews, ENABLED, false);
      //设置统一操作
      static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {
      @Override public void apply(View view, int index) {
      view.setEnabled(false);
      }
      };
      static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {
      @Override public void set(View view, Boolean value, int index) {
      view.setEnabled(value);
      }

由上面实例可以看出,ButterKnife 提供了Action和Setter接口,允许指定简单的行为;其次,Android Property 成员也可以与apply方法一起使用。

1
ButterKnife.apply(nameViews, View.ALPHA, 0.0f);

  1. 监听器绑定

    • 监听器也可以自动配置到方法上,传入的参数表示监听的对象。

      1
      2
      3
      4
      @OnClick(R.id.submit)
      public void submit(View view) {
      // TODO submit data to server...
      }
    • 监听器方法的参数是可选的,即可以无需添加参数。

      1
      2
      3
      4
      @OnClick(R.id.submit)
      public void submit() {
      // TODO submit data to server...
      }
    • 定义一个特定的类型,它会自动转换,需要注意的是,定义的参数必须是监听的对象或者其父类,否则会转换错误。

      1
      2
      3
      4
      @OnClick(R.id.submit)
      public void sayHi(Button button) {
      button.setText("Hello!");
      }
    • 同样,可以将一个方法配置给多个id,这里也有一点需要注意,传入的参数必须要是各个监听对象共同的父类。

      1
      2
      3
      4
      5
      6
      7
      8
      @OnClick({ R.id.door1, R.id.door2, R.id.door3 })
      public void pickDoor(DoorView door) {
      if (door.hasPrizeBehind()) {
      Toast.makeText(this, "You win!", LENGTH_SHORT).show();
      } else {
      Toast.makeText(this, "Try again", LENGTH_SHORT).show();
      }
      }
    • 自定义View可以通过不指定ID来绑定到自己的监听器。

      1
      2
      3
      4
      5
      6
      public class FancyButton extends Button {
      @OnClick
      public void onClick() {
      // TODO do something!
      }
      }
  2. 绑定解绑
    ButterKnife 8.4 相对于 ButterKnife 7.0 添加了解绑机制,要求Fragment在适当的时候进行解绑。
    Fragment具有与Activity不同的生命周期。 当在onCreateView中绑定Fragment时,需要在onDestroyView中将视图设置为null。 ButterKnife会在bind 时返回一个Unbinder实例。 在适当的生命周期回调中调用其unbind方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public class FancyFragment extends Fragment {
    @BindView(R.id.button1) Button button1;
    @BindView(R.id.button2) Button button2;
    private Unbinder unbinder;
    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    unbinder = ButterKnife.bind(this, view);
    // TODO Use fields...
    return view;
    }
    @Override public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
    }
    }
  3. 可选性绑定
    在使用过程中,ButterKnife 还考虑到了 绑定时出现绑定目标未找到的情况。默认情况下,未找到会直接抛出异常,如果需要避免抛出异常,ButterKnife也提供了结果方案,只需要 用 @Nullable 来注解 属性,或者使用 @Optional来注解方法即可,使用如下。

    1
    2
    3
    4
    @Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;
    @Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
    // TODO ...
    }
  4. ButterKnife.findById

    1
    2
    3
    4
    View view = LayoutInflater.from(context).inflate(R.layout.thing, null);
    TextView firstName = ButterKnife.findById(view, R.id.first_name);
    TextView lastName = ButterKnife.findById(view, R.id.last_name);
    ImageView photo = ButterKnife.findById(view, R.id.photo);
  5. 其他监听器
    ButterKnife 同时还提供了其他的监听器。

    这里我们以 onItemSelected 为例:

    1
    2
    3
    4
    5
    6
    7
    8
    @OnItemSelected(R.id.list_view)
    void onItemSelected(int position) {
    // TODO ...
    }
    @OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)
    void onNothingSelected() {
    // TODO ...
    }

方法的参数是可选的,但同时需要符合 注解参数的要求,不能多参或者出现参数类型不存在的问题,如果出现参数类型相同的情况,方法的参数会从左到右依次匹配。

总结:

本文例子 来源于 Butter Knife官网,文中的介绍也主要是根据官网给出的总结,并且加入了个人在使用过程中的一些看法,就算是一份学习笔记吧。