首次使用Butterknife替代findViewById遇异常,求解决方案(附类代码)
Hey Theo! 刚接触ButterKnife就踩坑太正常了,我当初也折腾过一阵。先别慌,咱们一步步排查常见的问题,大概率能解决你的运行时异常:
常见问题排查与解决思路
1. 依赖配置不全
ButterKnife需要同时配置核心依赖和注解处理器,很多新手容易漏掉后者:
- 检查你Module级别的
build.gradle,确保包含这两项(可以替换为最新稳定版本):
dependencies { implementation 'com.jakewharton:butterknife:10.2.3' annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3' }
- 如果是Kotlin项目,要把
annotationProcessor换成kapt,还要在文件顶部添加apply plugin: 'kotlin-kapt'
2. 忘记在生命周期中完成绑定
必须在合适的时机调用绑定方法,而且顺序不能错:
- Activity中:要在
setContentView之后调用ButterKnife.bind(this),示例:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); // 这行绝对不能少! }
- Fragment中:要在
onViewCreated里用ButterKnife.bind(this, view)绑定,示例:
@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); }
3. 注解使用错误
- 确认控件绑定用的是
@BindView(R.id.xxx),别写错成旧版的@Bind或者其他注解 - 如果绑定多个控件的列表,要用
@BindViews,变量类型对应List<View>或具体控件类型的列表 - 检查布局文件里的控件ID,必须和注解里的ID完全一致,大小写都不能错
4. 混淆配置缺失(如果开启了ProGuard)
要是你的项目开启了代码混淆,必须在混淆规则里添加ButterKnife的保护配置,否则运行时会找不到绑定类:
-keep class butterknife.** { *; } -dontwarn butterknife.internal.** -keep class **$$ViewBinder { *; } -keepclasseswithmembernames class * { @butterknife.* <fields>; } -keepclasseswithmembernames class * { @butterknife.* <methods>; }
5. 多模块项目的特殊处理
如果是多模块项目,每个用到ButterKnife的模块都要单独配置注解处理器,不能只在主模块配置哦。
要是你能把具体的异常信息(比如是NullPointerException还是IllegalStateException)贴出来,能更快定位问题,但先按上面的步骤排查,应该能解决大部分常见问题~
内容的提问来源于stack exchange,提问作者Theo
相关产品推荐
相关产品推荐

