关于ButterKnife 在module中使用问题

ButterKnife 在module中使用问题

  • 说道ButterKnife 框架给我们的日常开发带来的便利,不言而喻了。在Activity、fragment、adapter等等各种情景中的使用(使用方法以及原理在此不做讲解)。但是最近在做一个组件化开发过程中,遇到一个问题,那就是在module中,它无法读取到 id,具体什么情况呢,看下下图

  • Attribute value must be constant
    什么原因呢,Attribute value must be constant
    通过追踪源码发现, @BingView(int ResId)这个参数必须是 final 修饰的常量
    而打开R文件看看区别

  • app壳子程序中的R文件:
    app壳子程序中的R文件

  • module 中的R文件:
    module 中的R文件

很明显,module 中的R资源 Id 缺少 final 修饰,而ButterKnife 注解 资源 Id时,id 必须是final 修饰。
解决方法在下

  • 1、在app壳子程序的的 build.gradle中加入:
classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'

此处我用的是8.4.0版本,其他版本官方应该也有说明

  • 2、在module 中的build.gradle中加入:
apply plugin: 'com.jakewharton.butterknife'
dependencies {
	//butterknife8.4
    implementation 'com.jakewharton:butterknife:8.4.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}
  • 3、 同步一下

ok, 接下来你就可以使用 注解了,姿势是这样的:
在这里插入图片描述
你没有看错,这里是使用 R2, 而不是 R ,到此就完了。
啥 ? R2 哪来的 ? 为什么是R2 ? 哈哈哈,下次写ButterKnife 源码分析的时候会说明的。

如果写错或者问题,欢迎大佬指正留言指正

猜你喜欢

转载自blog.csdn.net/H1101370034/article/details/86065950