Android 多个Module使用ButterKnife出现的NullPointerException

ButterKnife项目地址:https://github.com/JakeWharton/butterknife

AndroidX按照正常的方式集成:

android {
  ...
  // Butterknife requires Java 8.
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
  implementation 'com.jakewharton:butterknife:10.1.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
}
buildscript {
  repositories {
    mavenCentral()
    google()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:10.1.0'
  }
}

集成完成以后,自动生成的BindView中的View 是Null,多方查找未果,结果在一个老的项目中找到了答案,于此记录一下;

Android 多个Module使用ButterKnife出现的NullPointerException_第1张图片

这个是我的项目结构,我把常用的一些工具类和常用的第三方放在了common模块中(ButterKnife也在这个模块中);

但是我在主模块app中使用ButterKnife生成的控件一直是Null

Android 多个Module使用ButterKnife出现的NullPointerException_第2张图片

etPhone、etPwd均是Null;

解决方法是在app模块的gradle中增加注解annotationProcessor(注解处理器)

annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'

也就是说,我在common模块中引入了ButterKnife,如果在app模块中使用的话,还要在app模块加入annotationProcessor,不然app模块没有办法根据注解生成Java或R文件;

如果加了这个还是null或报错,可以加上  apply plugin: 'com.jakewharton.butterknife' 试试;

Android 多个Module使用ButterKnife出现的NullPointerException_第3张图片

总结,使用ButterKnife的模块必须有注解处理器 annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'

类似使用到注解处理器的框架还有很多 ButterKnife、Glide 、Arouter、Dagger2等等。。。

 

你可能感兴趣的:(Android)