緒論:本人也是剛接觸ButterKnife理解不深刻。在這裏只給大家介紹用法:
作用是節省大量的findViewById();可以節省大量的代碼量,增加代碼的可讀性。
在這裏是說AS的用法:
對於As的小夥伴直接操作Gradle就可以了:
添加依賴:
compile 'com.jakewharton:butterknife:8.7.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'//這一個必須要加
接下來就可以在項目中使用了,
setContentView(R.layout.activity_main);
// ButterKnife.bind(this);這個一定要寫在setContentView()之後。
ButterKnife.bind(this);//this代表綁定的Activity
在Fragment中:
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;
}
}
在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);
}
}
}
接下來就可以對控件操作了:
@BindView(R.id.text)
TextView textView;
以上步驟完成之後就可以對控件做你想做的事情了!