大家都知道ButterKnife的方便,在activity中用一定是在setContentView之后才行
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
在build.gradle中添加依赖
implementation 'com.jakewharton:butterknife:8.7.0'
点击File->settings->plugins->,搜索下载这个插件,然后就可以很方便啦
然后右键点击想要加载控件的布局,比如R.layout.activity_main,选择Generate
在选择最后一行,然后选择需要添加的控件,直接OK
之前有遇到问题,在ViewHolder中或者Fragment中使用ButterKnife会加载不出来控件,那是因为太蠢了,新手嘛
像这种inflate的View,需要在Inflate后把view传到第二个参数
cacheView = inflater.inflate(R.layout.fragment_weather, container, false); unbinder = ButterKnife.bind(this, cacheView);
在ViewHolder中使用构造函数中传入View,然后在构造函数中bind
view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false); viewHolder = new ViewHolder(view);
static class ViewHolder { @BindView(R.id.tomorrow_date_text) TextView tomorrowDateText; @BindView(R.id.tomorrow_type_text) TextView tomorrowTypeText; @BindView(R.id.tomorrow_low_text) TextView tomorrowLowText; @BindView(R.id.tomorrow_high_text) TextView tomorrowHighText; public ViewHolder(View view) { ButterKnife.bind(this,view); } }
不过一般做项目都是BaseAcitvity的onCreate()中bind,onDestroy()中unbind,子类不用再bind。
就这样,遇到的问题记录一下。。。