ButterKnife是AndroidStudio中一個(gè)應(yīng)用非常廣的插件,有著藝術(shù)般的體驗(yàn),深受廣大開發(fā)者的喜愛,只需要3步即可配置成功,想要拋棄findViewById請(qǐng)跟我來代嗤。
1、首先先要下載ButterKnife
2缠借、安裝好插件之后干毅,在project中的build.gradle中的dependencies中添加:
classpath ‘com.neenbedankt.gradle.plugins:Android-apt:1.8’ // 添加這行
3、根據(jù)指定的位置插入代碼
applyplugin:'android-apt'//添加這行
compile'com.jakewharton:butterknife:8.5.1'//添加這行apt'com.jakewharton:butterknife-compiler:8.5.1'//添加這行
配置完成之后泼返,Sync Now一下硝逢,既可以開始使用,下圖是使用教程:
把光標(biāo)放在布局代碼上绅喉,按下Alt+Insert快捷鍵渠鸽,選擇“Generate Butterknife Injections”
@Override
protected void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);? ?
?setContentView(R.layout.activity_main);
// 綁定
ButterKnife.bind(this);
}
Unbinder unbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {? ?
?View containerView = inflater.inflate(R.layout.frag_home,null);
// 綁定
unbinder = ButterKnife.bind(this,containerView);
return containerView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
// 解綁
unbinder.unbind();
}
public class RecyclerHolder extends RecyclerView.ViewHolder{
@BindView(R.id.item_label)
TextView itemLabel;
public RecyclerHolder(View itemView) {
? ? ? ? ?super(itemView);
? ? ? ? ? ButterKnife.bind(this,itemView);
? ? ? ? }
}
綁定控件
@BindView(R.id.toolbar_title)
TextView toolbarTitle;