androidx使用ViewPager+tablayout报错:Caused by: android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class com.google.android.material.tabs.TabLayout Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class com.google.android.material.tabs.TabLayout
解决方案:
-
未正确添加 Material Components 依赖项
TabLayout
是 Material Components 库的一部分,如果未正确添加依赖项,会导致无法找到该类。 -
主题未正确设置
TabLayout
需要使用 Material 主题或继承自 Material 主题的 AppCompat 主题。 -
ProGuard 或 R8 混淆问题
如果启用了代码混淆,可能会导致TabLayout
类被错误地混淆或移除。 -
XML 布局文件中的命名空间问题
如果未正确声明命名空间,可能会导致无法解析TabLayout
。
我使用的方案:
确保使用正确的主题
在 res/values/styles.xml
中,确保你的应用主题继承自 Material Components 主题或 AppCompat 主题。例如:
<resources> <!-- 使用 Material Components 主题 --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- 自定义主题属性 --> </style> </resources>
或者在 AndroidManifest.xml
中确保应用使用了正确的主题:
<application android:theme="@style/AppTheme"> <!-- 其他配置 --> </application>