解決ButterKnife8.4版本 @BindView報空指針異常


BindView是Android view的一個工具,不僅使用特別方便,還減少了代碼。

原生寫法:

TextView text = FindViewById(R.id.text_view);

BindView寫法

在頂部定義變量時添加

@BindView(R.id.tvMainTime)
TextView mTvMainTime;

 

使用方法:

1、在app的build.gradle中添加編譯和聲明

compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'

在頂部添加請求

apply plugin: 'com.neenbedankt.android-apt'

2、在項目的build.gradle中添加附屬

dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}

3、在需要加載布局的地方進行綁定(拿MainActivity舉例),在onCreate中添加

ButterKnife.bind(this);

至此就可以正常使用了,報空指針的原因是沒在調用BindView時進行綁定,綁定后就正常使用了,希望能幫助到你。

 

注意:以上配置為JavaVersion.VERSION_1_7 配置方法,JavaVersion.VERSION_1_8配置詳見下文:

1、app的 build.gradle中刪除 apply plugin: 'com.neenbedankt.android-apt'

2、dependencies里的classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'改為:annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

否則build時不通過,會報 Gradle sync failed: Could not get unknown property 'classpath' for task ':app:transformJackWithJackForHuzhouDebug' of type com.android.build.gradle.internal.pipeline.TransformTask.




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM