解决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.



posted @ 2021-12-03 17:48  渣娃  阅读(1089)  评论(0编辑  收藏  举报