使用window.setDecorFitsSystemWindows(false)后BottomAppBar高度异常增大问题
问题:透明状态栏下BottomAppBar内边距加倍的原因及解决
我通过window.setDecorFitsSystemWindows(false)和statusBarColor = Color.TRANSPARENT实现了透明状态栏,但引入BottomAppBar后,它的内边距明显加倍了,请问这是什么原因?
状态截图
- 开启
window.setDecorFitsSystemWindows(false)时的状态:
- 未开启
window.setDecorFitsSystemWindows(false)时的状态:
主活动布局代码
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ActivityMain"> <androidx.fragment.app.FragmentContainerView android:id="@+id/fragmentContainer" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" app:defaultNavHost="true" app:navGraph="@navigation/main" /> <com.google.android.material.bottomappbar.BottomAppBar android:id="@+id/bottomAppBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:contentInsetEnd="0dp" app:contentInsetStart="0dp" app:elevation="1dp"> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNavigation" android:layout_width="match_parent" android:layout_height="wrap_content" app:itemHorizontalTranslationEnabled="false" android:background="@android:color/transparent" app:elevation="0dp" app:labelVisibilityMode="auto" app:menu="@menu/nav_bar_menu" /> </com.google.android.material.bottomappbar.BottomAppBar> </androidx.coordinatorlayout.widget.CoordinatorLayout>
原因分析及解决方法
核心原因
设置window.setDecorFitsSystemWindows(false)后,系统不再自动处理布局与系统栏的间距,控制权完全交予开发者。而BottomAppBar本身默认会自动添加适配系统导航栏的内边距,关闭系统自动适配后,它可能重复计算或叠加了额外内边距,再加上嵌套在其中的BottomNavigationView自带默认内边距,两者叠加就出现了内边距加倍的效果。
解决步骤
禁用BottomAppBar的系统窗口适配
在BottomAppBar属性中添加android:fitsSystemWindows="false",阻止它自动适配系统窗口间距:<com.google.android.material.bottomappbar.BottomAppBar android:id="@+id/bottomAppBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:fitsSystemWindows="false" app:contentInsetEnd="0dp" app:contentInsetStart="0dp" app:elevation="1dp">清除BottomNavigationView的多余内边距
给BottomNavigationView添加app:itemPaddingHorizontal="0dp"去掉横向内边距,也可以根据实际效果设置android:padding="0dp":<com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNavigation" android:layout_width="match_parent" android:layout_height="wrap_content" app:itemHorizontalTranslationEnabled="false" android:background="@android:color/transparent" app:elevation="0dp" app:labelVisibilityMode="auto" app:menu="@menu/nav_bar_menu" app:itemPaddingHorizontal="0dp" />检查主题配置
确认App主题没有给BottomAppBar或BottomNavigationView设置默认内边距,避免样式层面的额外影响。
内容的提问来源于stack exchange,提问作者David Trpcevski
相关产品推荐
相关产品推荐

