ButterKnife,这个方便findViewById而使用的库,无数的应用在使用它,以注解来实现的他,对应用的性能影响几乎可以忽略,可以放心使用。
使用:
compile 'com.jakewharton:butterknife:7.0.1'
我们常用的无非就是:
@Bind(R.id.name)
View name @OnClick(R.id.name)
public void click(){}
其实他的功能远不仅仅如此,常用的还有下面点是你需要知道的。
1.对多个view的点击事件监听:
@OnClick({ R.id.button1, R.id.button2, R.id.button2 })
public void buttonClicks(View view) { switch(view.getId()) {
case R.id.button1:
Toast.makeText(this, "Button1 clicked!", LENGTH_SHORT).show();
break; case R.id.button1:
Toast.makeText(this, "Button2 Clicked!", LENGTH_SHORT).show();
break; case R.id.button1:
Toast.makeText(this, "Button3 clicked!", LENGTH_SHORT).show();
break; }
}
2.长按以及选中Item等的监听:
@OnLongClick(R.id.hello) boolean sayGetOffMe() {
Toast.makeText(this, "Let go of me!", LENGTH_SHORT).show();
return true;
} @OnItemClick(R.id.list_of_things) void onItemClick(int position) {
Toast.makeText(this, "You clicked: " + adapter.getItem(position), LENGTH_SHORT).show();
} @OnItemSelected({R.id.spinnerCountry})
void onItemSelected(Spinner spinner, int position) { } @OnItemSelected(value=R.id.spinnerCountry, callback = OnItemSelected.Callback.NOTHING_SELECTED)
void onNothingSelected() { } *****
@OnLongClick
@OnPageChange
OnPageChange.Callback
@OnTextChanged
@OnTextChanged.Callback
@OnTouch
@OnItemLongClick
@OnCheckedChanged
3.绑定资源文件,也可以这样玩:
@BindColor(R.color.red) int red;
@BindString(R.string.activity_title) String activityTitle;
@BindDimen(R.dimen.btn_horizontal_margin_common) Float btnHorizontalMarginCommon;
@BindDrawable(R.drawable.ic_instructions) Drawable iconInstructions;
4.绑定多个view到List:
Bind({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;
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);
}
};
5.设置View的属性:
ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
6.如果对findViewById怀念,你也可以这样玩:
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);
7.非空判断,如果view为空会抛出异常,但是你可以这样玩呀:
@Nullable @Bind(R.id.edUserName)
EditText edUserName;