Android Butterknife 使用

ButterKnife是AndroidStudio中一個(gè)應(yīng)用非常廣的插件,有著藝術(shù)般的體驗(yàn),深受廣大開(kāi)發(fā)者的喜愛(ài),只需要3步即可配置成功,想要拋棄findViewById請(qǐng)跟我來(lái)。

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一下,既可以開(kāi)始使用,下圖是使用教程:

把光標(biāo)放在布局代碼上,按下Alt+Insert快捷鍵,選擇“Generate Butterknife Injections”

綁定Activity

@Override

protected void onCreate(@Nullable Bundle savedInstanceState){

super.onCreate(savedInstanceState);? ?

?setContentView(R.layout.activity_main);

// 綁定

ButterKnife.bind(this);

}

綁定Fragment

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();

}

綁定ViewHolder

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;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容