转载请注明出处 http://blog.csdn.net/qq_31715429/article/details/51823000
本文出自:猴菇先生的博客
1.在项目的build.gradle文件的相应位置中添加
...
dependencies{
...
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
...
2.在app中的build.gradle文件相应位置中添加
...
apply plugin: 'com.neenbedankt.android-apt'
...
dependencies {
...
//反射注解
compile 'com.jakewharton:butterknife:8.0.1'
apt 'com.jakewharton:butterknife-compiler:8.0.1'
}
3.在使用注解的activity中
public class MainActivity extends BaseActivity {
@BindView(R.id.menu)//绑定控件
ImageView mMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);//绑定
}
@OnClick(R.id.menu)//点击事件
public void openMenu() {
ToastUtil.show(this, "设置");
}
4.在使用注解的fragment中
public class MainFragment extends Fragment{
Unbinder unbinder;
@BindView(R.id.list)//绑定控件
ListView mList;
@BindViews({R.id.img1, R.id.img2, R.id.img3, R.id.img4})//绑定多个控件
List<ImageView> mImgList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
unbinder = ButterKnife.bind(this, view);//绑定
MainAdapter adapter = new MainAdapter (getActivity(), data);
mList.setAdapter(adapter);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();//解绑
}
}
5.在使用注解的adapter中
public class MainAdapter extends BaseAdapter {
private Context mContext;
private List<Data> mData;
private LayoutInflater inflater;
public MainAdapter(Context mContext, List<Data> mData) {
this.mContext = mContext;
this.mData= mData;
inflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.adapter_main, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Glide.with(mContext).load(mData.getIcon()).into(holder.icon);
holder.title.setText(mFemaleRank.get(position).getTitle());
return convertView;
}
public class ViewHolder {
@BindView(R.id.icon)//绑定控件
ImageView icon;
@BindView(R.id.title)
TextView title;
public ViewHolder(View view) {//构造方法中传入convertView
ButterKnife.bind(this, view);//绑定
}
}
}
注意
1.Activity ButterKnife.bind(this);必须在setContentView();之后,且父类bind绑定后,子类不需要再bind
2.Fragment ButterKnife.bind(this, mRootView);
3.属性布局不能用private or static 修饰,否则会报错
4.setContentView()不能通过注解实现。(其他的有些注解框架可以)
Zelezny插件的使用
在AndroidStudio->File->Settings->Plugins->搜索Zelezny下载添加就行 ,可以快速生成对应组件的实例对象,不用手动写。使用时,在要导入注解的Activity 或 Fragment 或 ViewHolder的layout资源代码上,右键——>Generate——Generate ButterKnife Injections,然后就出现如图的选择框。(此动态图来自官网)