返回

Android 11 暗黑模式下 BottomNavigationView 样式问题详解及解决方法

Android

Android 11 设备暗黑模式下 BottomNavigationView 样式问题

简介

在 Android 11 设备暗黑模式下使用 BottomNavigationView 时,可能会遇到一个错误,提示应用程序主题需要为 Theme.AppCompat(或其后代)。本文将深入分析此问题的原因,并提供两种解决方法。

问题

当在 Android 11 及更高版本的设备暗黑模式下使用 BottomNavigationView 时,可能会遇到以下错误:

Caused by: android.view.InflateException: Binary XML file line #25 in com.example:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView

Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).

分析

此问题在 Android 11 及更高版本的暗黑模式下出现,但在浅色模式下不会出现。这表明底层主题设置存在差异。

原因

在 Android 11 及更高版本的 Material Components 1.11.0 及以下版本中,存在一个错误,导致此问题。当应用程序主题设置为 Theme.MaterialComponents.DayNight.NoActionBarTheme.Material3.DayNight.NoActionBar 时,就会出现此错误。

解决方法

有两种方法可以解决此问题:

  1. 更新 Material Components 版本: 更新到 Material Components 1.12.0 或更高版本,该版本已修复了此错误。

  2. 使用以下解决方法:

    • 在应用程序主题中添加 android:windowLightNavigationBar 属性,设置为 true
    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="android:windowLightNavigationBar">true</item>
    </style>
    
    • BottomNavigationView 中添加 app:labelVisibilityMode="labeled" 属性:
    <com.google.android.material.bottomnavigation.BottomNavigationView
        ...
        app:labelVisibilityMode="labeled"
        ... />
    

其他注意事项

  • 确保在 gradle 文件中更新 Material Components 的版本:

    implementation 'com.google.android.material:material:1.12.0'
    
  • 确保应用程序的最小 SDK 版本设置为 21 或更高版本。

  • BottomNavigationView 中使用 app:itemActiveIndicatorStyle 属性来自定义活动指示器。

  • 使用 app:itemIconTintapp:itemTextColor 属性自定义图标和文本颜色。

结论

本文分析了在 Android 11 及更高版本的暗黑模式下使用 BottomNavigationView 时遇到的样式问题。通过更新 Material Components 版本或使用提供的解决方法,可以解决此问题。此外,我们还提供了其他注意事项,以确保正确实现。

常见问题解答

  1. 此问题为什么只在暗黑模式下出现?

    • Material Components 中的一个错误导致了这个问题,它会在 Android 11 及更高版本的暗黑模式下触发。
  2. 是否可以继续使用 Material Components 1.11.0 及以下版本?

    • 可以,但是你需要使用提供的解决方法来避免这个问题。
  3. 更新 Material Components 版本后,还需要做其他更改吗?

    • 通常不需要,但是建议检查是否有其他依赖项受 Material Components 更新的影响。
  4. 我是否需要设置 android:windowLightNavigationBar 属性?

    • 是的,这个属性在使用解决方法时是必需的。
  5. 我是否可以在 BottomNavigationView 中自定义其他元素?

    • 是的,你可以使用 app:itemActiveIndicatorStyleapp:itemIconTintapp:itemTextColor 等属性自定义活动指示器、图标和文本颜色。