Android BottomNavigationView运行报NoSuchMethodError异常求助
你遇到的这个java.lang.NoSuchMethodError是非常典型的Android Support库版本不兼容问题,从异常栈和你的build.gradle配置来看,核心问题出在各个Support组件的版本号不统一,导致类加载时找不到对应的方法实现。
问题根源分析
异常提示找不到android.support.v7.widget.ViewUtils.combineMeasuredStates()方法,这个方法在不同版本的Support库中存在版本差异。你的依赖里同时混用了多个Support库版本:
appcompat-v7:25.0.0、design:25.0.0support-v4:25.3.1、recyclerview-v7:25.3.1mediarouter-v7:25.2.0
这种版本混乱会导致Gradle构建时引入多个版本的Support库类,ClassLoader加载了旧版本的ViewUtils类,但代码却调用了新版本才有的方法,最终抛出NoSuchMethodError。
解决步骤
1. 统一所有Support库的版本号
把所有com.android.support开头的依赖统一为同一个版本(建议选你现有依赖中最高的兼容版本,比如25.3.1),修改后的依赖片段如下:
dependencies { implementation 'com.google.android.gms:play-services-maps:11.8.0' compile fileTree(include: ['*.jar'], dir: 'libs') compile project(':ccp') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) // 统一所有Support库版本为25.3.1 compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:support-v4:25.3.1' compile 'com.android.support:design:25.3.1' compile 'com.android.support:recyclerview-v7:25.3.1' compile 'com.android.support:mediarouter-v7:25.3.1' compile 'com.android.support:animated-vector-drawable:25.3.1' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.facebook.android:facebook-android-sdk:[4,5)' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.squareup:otto:1.3.8' compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.squareup.okhttp3:logging-interceptor:3.9.0' compile 'com.squareup.okhttp:okhttp:2.7.5' compile 'com.google.code.gson:gson:2.7' compile 'com.android.support:multidex:1.0.0' // 排除第三方库自带的Support依赖,避免冲突 compile ('com.roughike:bottom-bar:1.4.0.1') { exclude group: 'com.android.support' } compile ('com.github.ittianyu:BottomNavigationViewEx:1.2.4') { exclude group: 'com.android.support', module: 'design' } compile 'com.facebook.android:account-kit-sdk:4.+' compile 'com.google.firebase:firebase-core:11.8.0' compile 'com.google.firebase:firebase-messaging:11.8.0' compile 'com.github.moondroid.coverflow:library:1.0' testCompile 'junit:junit:4.12' compile 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' }
2. 排除第三方库的隐性Support依赖
像BottomNavigationViewEx、bottom-bar这类第三方库可能自带了Support库依赖,会和你的项目版本冲突,通过exclude语句可以强制它们使用你项目中统一的Support版本。
3. 清理并重建项目
修改完依赖后,执行以下操作确保构建缓存被清理:
- 点击Android Studio顶部菜单的
Build -> Clean Project - 然后选择
Build -> Rebuild Project - 必要时可以手动删除项目根目录下的
build文件夹和模块下的build文件夹,再重新构建
4. 检查Firebase/Play Services兼容性
你使用的play-services-maps:11.8.0和Firebase版本需要和Support库版本兼容,11.8.0对应的最低Support库版本是25.4.0,如果统一到25.3.1后仍有问题,可以考虑把Firebase/Play Services版本调整为11.0.4(和旧Support库兼容),或者把Support库版本升级到25.4.0及以上。
验证
完成上述步骤后,重新运行应用,NoSuchMethodError应该会消失,BottomNavigationView可以正常加载。
内容的提问来源于stack exchange,提问作者Sunil P

