ButterKnife完全解析

来源:互联网 发布:管家婆支持远程网络吗 编辑:程序博客网 时间:2024/05/29 17:32

原文链接:http://jakewharton.github.io/butterknife/

ButterKnife使用@Bind+控件ID的成员变量注解,可以自动转换你的布局中的控件。

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

相比缓慢的反射,生成的代码执行控件查找操作。你可以看见并调试绑定代表生成的代码。

上面例子生成的代码基本等同于下面

public void bind(ExampleActivity activity) {  activity.subtitle = (android.widget.TextView) activity.findViewById(2130968578);  activity.footer = (android.widget.TextView) activity.findViewById(2130968579);  activity.title = (android.widget.TextView) activity.findViewById(2130968577);}

资源绑定

绑定预定义的资源,使用@BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString,会绑定一个R.bool ID(或者是你自定义的类型)和它对应的字段。

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

非Activity绑定

你还可以提供你自己View,来绑定任意的对象

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

另一个用途是简化list中Adapter的ViewHolder

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

通过给定的例子,你可以看到这个实现。

ButterKnife.bind可以在任何使用findViewById的地方调用。

其他提供的绑定API

  • 绑定任意使用Activity作为根布局的对象。如果你使用MVC模式,你可以用ButterKnife.bind(this, activity)来绑定控制器。
  • 使用ButterKnife.bind(this)绑定一个控件的子元素。如果你在布局中使用标签并在自定义控件构造器中填充该布局,你可以立即调用该方法。或者,自定义控件类型从XML中填充布局,在onFinishInflate()回调中调用该方法。

控件列表

你可以组合多个控件为一个List或者数组

@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })List<EditText> nameViews;// apply方法允许你同时操作一个List中的所有控件ButterKnife.apply(nameViews, DISABLE);ButterKnife.apply(nameViews, ENABLED, false);// Action和Setter接口允许指定简单行为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);  }};

apply方法也可以使用Android属性

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

绑定监听器(Listener)

监听器(Listener)也可以自动的配置到方法上

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

所有监听器(Listener)方法的参数都是可选的

@OnClick(R.id.submit)public void submit() {  // TODO submit data to server...}

定义一个具体的类型,也会被自动转换

@OnClick(R.id.submit)public void sayHi(Button button) {  button.setText("Hello!");}

为多个ID指定一个共同的事件监听绑定

@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可以绑定自己的监听器(Listener)而不用指定ID

public class FancyButton extends Button {  @OnClick  public void onClick() {    // TODO do something!  }}

绑定重置

Fragment相比Activity有不同的生命周期。应在onCreateView方法中完成绑定,并在onDestroy方法中设置绑定的View为null。当你调用bind,ButterKnife会返回一个unbinder实例,调用它的unbind方法在相对应的生命周期回调方法中。

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

可选绑定

默认情况下,@Bind和监听器绑定都是必须的,目标控件找不到时会抛出异常。

为了抑制这个行为并创建一个可选的绑定,给成员变量加上@Nullable注解或者给方法加上@Optional注解

注意:任何@Nullable注解都可以使用在成员变量上。推荐使用Android “support-annotations” 库中的@Nullable注解。

@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {  // TODO ...}

多方法的监听器

对应监听器有多个回调的方法注解,可以绑定其中任意规格。每个注解都有一个默认绑定的回调。使用回调参数指定一个替代的回调。

@OnItemSelected(R.id.list_view)void onItemSelected(int position) {  // TODO ...}@OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)void onNothingSelected() {  // TODO ...}

附:

在View,Activity或者Dialog这些需要查找控件的地方,可以使用findById方法简化代码。它使用泛型来推断返回类型并自动执行转换。

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);// 添加一个ButterKnife.findById的静态导入,享受更多的乐趣

添加Gradle依赖

compile ‘com.jakewharton:butterknife:8.0.1’
apt ‘com.jakewharton:butterknife-compiler:8.0.1’

0 0
原创粉丝点击