版權(quán)聲明
原創(chuàng)作者:谷哥的小弟
博客地址:http://blog.csdn.net/lfdfhl
參考資料
準(zhǔn)備工作
- 為Android Studio安裝插件Butterknife Zelezny
- 在build.gradle的dependencies{}中加入
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
使用方式
- 綁定控件
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...
}
}
- 綁定資源
@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;
@BindDimen(R.dimen.spacer) Float spacer;
// ...
}
- 綁定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 b) {
View view = inflater.inflate(R.layout.fragment, container, false);
unbinder = ButterKnife.bind(this, view);
// TODO Use fields...
return view;
}
@Override public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
在Fragment的onCreateView()中設(shè)置綁定心肪,onDestroyView()中解綁
- 綁定Adapter
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);
}
}
}
- 綁定Click事件監(jiān)聽
@OnClick(R.id.textView)
public void clickView(){
Toast.makeText(this,"click",Toast.LENGTH_SHORT).show();
}
請注意方法應(yīng)該是public或者static的