butterknife which uses annotation processing to generate boilerplate code for you. Jar包下载。
一、图文配置Eclipse
1、将jar放于工程的libs目录下
2、选择工程的 poperties
3、找到如下目录并购选Enable project specific settings
4、勾选Factory Path 中的Enable project specific settings
5、Add JARs
这样就完成了ButterKnife的配置了。
二、ButterKnife的使用
1、首先是调用ButterKnife.inject(params)方法
a、在onCreate中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
// Contrived code to use the "injected" views.
title.setText("Butter Knife");
subtitle.setText("View \"injection\" for Android.");
footer.setText("by Jake Wharton");
hello.setText("Say Hello");
adapter = new SimpleAdapter(this);
listOfThings.setAdapter(adapter);
}
b、在ListView的Adapter中
static class ViewHolder {
ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
2、完成类似findViewById的操作:
TextView title = (TextView) findViewById(R.id.title);//原来的写法,写在方法内
@InjectView(R.id.title) TextView title;//现在的写法,写在方法外
@InjectViews({ R.id.title, R.id.subtitle, R.id.hello })
List<View> headerViews;//同时findViewById多个ID,并放入一个集合
3、将ID与各种方法关联:
@OnClick(R.id.title) void sayHello() {//节省了传统方法的设置监听
Toast.makeText(this, "Hello, views!", LENGTH_SHORT).show();
}
@OnItemClick(R.id.list_of_things) void onItemClick(int position) {//节省了listView的对item监听句子
Toast.makeText(this, "You clicked: " + adapter.getItem(position), LENGTH_SHORT).show();
}
@InjectView(R.id.title) TextView title;
@InjectView(R.id.subtitle) TextView subtitle;
@InjectView(R.id.hello) Button hello;
@InjectView(R.id.list_of_things) ListView listOfThings;
@InjectView(R.id.footer) TextView footer;
@InjectViews({ R.id.title, R.id.subtitle, R.id.hello })
List<View> headerViews;
private SimpleAdapter adapter;
@OnClick(R.id.hello) void sayHello() {
Toast.makeText(this, "Hello, views!", LENGTH_SHORT).show();
}
@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();
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
// Contrived code to use the "injected" views.
title.setText("Butter Knife");
subtitle.setText("View \"injection\" for Android.");
footer.setText("by Jake Wharton");
hello.setText("Say Hello");
adapter = new SimpleAdapter(this);
listOfThings.setAdapter(adapter);
}