隐藏系统底部导航栏后,如何让自定义底部导航贴紧屏幕底部?
实现自定义底部导航贴紧屏幕底部(隐藏系统导航栏后)
一、调整Window配置,让布局延伸到系统导航栏区域
在Activity的onCreate方法中添加以下配置,确保布局可以延伸到屏幕最底部:
// 让布局延伸到系统状态栏和导航栏下方 window.setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS ) // 关闭系统自动添加内边距的行为 window.decorView.fitsSystemWindows = false
二、修正隐藏系统导航栏的代码(兼容新旧Android版本)
旧的systemUiVisibility在Android 11(API 30)后已废弃,以下是兼容各版本的实现:
val currentApiVersion = Build.VERSION.SDK_INT if (currentApiVersion >= Build.VERSION_CODES.R) { // Android 11及以上版本 window.insetsController?.let { it.hide(WindowInsets.Type.navigationBars() or WindowInsets.Type.statusBars()) it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } } else { // Android 10及以下版本 val flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY window.decorView.systemUiVisibility = flags window.decorView.setOnSystemUiVisibilityChangeListener { visibility -> if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) { window.decorView.systemUiVisibility = flags } } }
三、优化布局配置
给根布局和自定义底部导航添加属性,确保贴紧底部:
<androidx.constraintlayout.widget.ConstraintLayout 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" android:fitsSystemWindows="false" tools:context=".MainActivity"> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNavigationView" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:menu="@menu/bottom_nav" android:fitsSystemWindows="false" app:layout_insetEdge="bottom"/> </androidx.constraintlayout.widget.ConstraintLayout>
四、关键原理说明
FLAG_LAYOUT_NO_LIMITS:解除Window布局对系统状态栏、导航栏的区域限制,让布局可以延伸到这些区域下方fitsSystemWindows="false":关闭系统自动给布局添加内边距的逻辑,避免自定义导航栏被顶起- 多版本兼容的导航栏隐藏逻辑:保证在不同Android版本下,系统导航栏都能稳定隐藏,同时让自定义导航栏完全贴紧屏幕底部
内容的提问来源于stack exchange,提问作者Captai-N
相关产品推荐
相关产品推荐

