Butterknife安裝步驟:
- 首先要知道在Studio和項(xiàng)目中都需要安裝butterknife插件;
因?yàn)檫@里邊用到了注解,所以需要apt (下邊會(huì)介紹),那么就需要在build.gradle中設(shè)置三處地方,否則會(huì)不生效或空指針錯(cuò)誤
a、apply plugin:'android-apt'
b、 dependencies {
??????classpath 'com.android.tools.build:gradle:2.3.0'
??????classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
兩個(gè)build.gradle文件中任選其一放置即可
??c、dependencies {
??????compile 'com.jakewharton:butterknife:8.5.1'
?? apt 'com.jakewharton:butterknife-compiler:8.5.1'
??}
Butterknife使用時(shí)注意:
Activity ButterKnife.bind(this);必須在setContentView();之后,且父類bind綁定后,子類不需要再bind
Fragment ButterKnife.bind(this, mRootView);
屬性布局的變量修飾符不能用private or static 修飾,否則會(huì)報(bào)錯(cuò)
setContentView()不能通過注解實(shí)現(xiàn)。
ButterKnife已經(jīng)更新到版本7.0.1了,以前的版本中叫做@InjectView了,而現(xiàn)在改用叫@Bind,更加貼合語義。
在Fragment生命周期中,onDestoryView也需要Butterknife.unbind(this)
ButterKnife不能在你的library module中使用! 這是因?yàn)槟愕膌ibrary中的R字段的id值不是final類型的,但你自己的應(yīng)用module中確是final類型的。
- APT (Annotation Processing Tool )注解處理工具 :
可以在編譯時(shí)處理注解,即在編譯時(shí)期掃描處理源代碼中的注解信息,并根據(jù)注解信息生成文件。Android上各種主流庫都用了APT來實(shí)現(xiàn),比如Dagger、ButterKnife、AndroidAnnotation、EventBus等。