ButterKnife

在开发过程中,总是会写大量的findViewById和点击事件,ButterKnife通过依赖注入帮助开发者省去初始化控件等重复性工作。ButterKnife是依赖注入中相对简单易懂的很不错的开源框架。

以下内容基于官网8.8.1版本的文档翻译出来的基本使用方法。官网地址:http://jakewharton.github.io/butterknife/

引用ButterKnife

在build.gradle中添加依赖:

implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

绑定视图

通过@BindView(view ID),ButterKnife可以找到并自动转换成相应的Layout中的View,自动绑定相应的控件。如下:

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);   //在Activity中绑定ButterKnife
    // TODO Use fields...
  }
}

ButterKnife帮我们完成了视图查找相关工作,上面示例生成的代码大致相当于以下代码:

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视图

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

ViewHolder绑定

可用来简化List Adaper的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。

其他的绑定APIS:

  • 使用Activity为根视图绑定任意对象时,如果使用的是MVC模式,可以调用ButterKnife.bind(this, activity)来绑定Controller。
  • 使用ButterKnife.bind(this)绑定一个view的子节点字段。如果在layout中用了<merge>标签,并在自定义View的构造函数中inflate填充,可在填充后立即使用。另外,从XML inflate来的自定义view类型,可以在onFinishInflate回调方法中使用它。

绑定控件ID直接将控件添加至集合或数组中

//nameViews的集中中添加了三个edittext对象
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;

//apply方法允许一次对列表中的所有视图进行操作,统一设置View可编辑、不可编辑
ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);
//以下DISABLE与ENABLED是上述接口的实现类,表示统一设置view集合的对应属性
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.apply(nameViews, View.ALPHA, 0.0f);

监听器绑定

直接绑定点击事件到一个方法

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

所有监听方法的参数是可选的

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

定义一个指定类型,它将被自动转换

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

多个控件统一处理同一个事件

@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绑定监听器

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

绑定重置、解绑

Fragments的生命周期不同于Activity。在onCreateView中绑定一个Fragment,在onDestroyView中将view设置为null。当调用bind来为Fragment绑定ButterKnife时,会返回一个Unbinder的实例。

在适当的生命周期(onDestroyView)回调中调用它的unbind方法进行Fragment解绑。

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和监听器绑定是需要的。但是如果找不到目标View便会抛出异常。

要禁止这种行为并创建可选绑定,可添加@Nullable注解到字段中,或者@Optional注解到方法中。让注入变成选择性的,如果目标View存在则注入,不存在则什么事情都不做。

任何被命名为@Nullable的注解都可以用于成员变量。鼓励使用@Nullable注解,此注解在Android的"support-annotations"库中。

使用方法如下:

@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;

@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
  // TODO ...
}

Listener中多方法注解

对应的监听器有多个回调,可用于绑定到其中任何一个。每个注解都有一个它绑定的默认回调。使用回调参数指定一个替换

@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
  // TODO ...
}

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

ButterKnife代码混淆

-keep class butterknife.** { *; } 
-dontwarn butterknife.internal.** 
-keep class **$$ViewBinder { *; }
-keepclasseswithmembernames class * { @butterknife.* <fields>; } 
-keepclasseswithmembernames class * { @butterknife.* <methods>; }

ButterKnife优势

1.强大的View绑定和Click事件处理功能,简化代码,提升开发效率

2.方便的处理Adapter里的ViewHolder绑定问题

3.运行时不会影响APP效率,使用配置方便

4.代码清晰,可读性强

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值