原文链接:http://jakewharton.github.io/butterknife/
github地址:https://github.com/JakeWharton/butterknife
ButterKnife使用@BindView和view ID 注解成员变量,自动地绑定你布局中对应的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);
// TODO Use fields...
}
}
code通过view查找产生,不是采用缓慢的反射机制,
上面绑定view的例子粗略地等同于下面的代码:
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 ,采用对应的注解来绑定不同类型的成员变量
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
// ...
}
你可以绑定任意的objects,通过使用你自己的 view root
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);
}
}
}
可以在提供的示例中查看具体的使用方法
在你使用到findViewById的地方调用ButterKnife.bind
其他提供的绑定APIS:
使用activity作为view root绑定任意的objects,如果你使用MVC,你可以通过使用Controller的activity,ButterKnife.bind(this, activity),绑定controller
使用ButterKnife(this)把view’s children 绑定到成员变量中,如果你在布局中使用标签,以及加载一个custom view的构造函数,可以在加载之后使用这个注解。可选择地,从XML中加载custom view可以在onFinishInflate()回调中使用注解;(原句:Bind a view’s children into fields using ButterKnife.bind(this). If you use tags in a layout and inflate in a custom view constructor you can call this immediately after. Alternatively, custom view types inflated from XML can use it in the onFinishInflate() callback.)
你可以同时把多个view绑定到List和Array中
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List nameViews;
apply方法同时对一个list中的所有view做处理
ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);
Action 与 Setter接口允许指定简单的behavior
static final ButterKnife.Action DISABLE = new ButterKnife.Action() {
@Override public void apply(View view, int index) {
view.setEnabled(false);
}
};
static final ButterKnife.Setter ENABLED = new ButterKnife.Setter() {
@Override public void set(View view, Boolean value, int index) {
view.setEnabled(value);
}
};
apply方法中也可以使用到一个android Property(属性)
ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
listeners可以自动地配置在methods上面
@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();
}
}
Custom Views(自定义view) 绑定listeners时,不用指定ID
public class FancyButton extends Button {
@OnClick
public void onClick() {
// TODO do something!
}
}
fragments具有和activities不同的生命周期,对于fragment而言,在onCreateView中进行绑定,在onDestroyView中解除绑定,当你进行绑定的时候,Butter Knife返回一个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和listener绑定 是需要的,当绑定的view没有找到时,会抛出一个异常,为了避免这种情况的发生,创造了optional binding,通过添加一个@Nullable 注解到成员变量中或者添加一个@Optional 注解到方法上;
@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;
@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
// TODO ...
}
方法注解的监听器有多个回调接口,可以与其中的任何一个进行绑定,每一个注解绑定有一个默认的回调,可以使用callback参数,指定一个回调;
@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
// TODO ...
}
@OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)
void onNothingSelected() {
// TODO ...
}
Butter knife也包含findById方法在View ,Activity or Dialog中查找view,可以简化代码,它利用泛型推断出返回的类型,可以自动的进行类型转换;
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);
Gradle
compile 'com.jakewharton:butterknife:(insert latest version)'
annotationProcessor 'com.jakewharton:butterknife-compiler:(insert latest version)'
如有不足的地方,欢迎留言指出。。。