Android中setOnApplyWindowInsetsListeners触发需setDecorFitsSystemWindows(false)但Toolbar与状态栏重叠
解决WindowInsets监听键盘与系统栏重叠的问题
问题根源
默认情况下Android的decorFitsSystemWindows为true,系统会自动把布局内容限制在安全区域内,同时拦截了输入法(IME)的Insets传递,所以你的EditText监听不到键盘状态。关闭setDecorFitsSystemWindows(window, false)后,Insets会直接传递给子View,虽然能监听键盘,但系统不再自动处理安全区域,导致Toolbar和底部导航栏与状态栏/导航栏重叠。
解决方案
保留setDecorFitsSystemWindows(window, false),手动给需要避开系统栏的View添加Insets适配,同时保留键盘监听逻辑:
1. 适配Toolbar和底部导航栏
用ViewCompat的Insets监听(兼容低版本),给Toolbar和底部导航栏设置对应padding,避开状态栏和导航栏:
适配Toolbar
ViewCompat.setOnApplyWindowInsetsListener(viewBinding.toolbar) { view, insets -> val systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars()) // 给Toolbar顶部添加状态栏高度的padding view.setPadding( systemBarsInsets.left, systemBarsInsets.top, systemBarsInsets.right, systemBarsInsets.bottom ) insets }
适配底部导航栏
ViewCompat.setOnApplyWindowInsetsListener(viewBinding.bottomNavigation) { view, insets -> val systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars()) // 给底部导航栏底部添加导航栏高度的padding view.setPadding( systemBarsInsets.left, 0, systemBarsInsets.right, systemBarsInsets.bottom ) insets }
2. 保留键盘监听逻辑
你的EditText监听代码可以正常保留,现在能触发键盘可见状态的判断:
viewBinding.etAmount.setOnApplyWindowInsetsListener { v, insets -> val imeVisible = insets.isVisible(WindowInsets.Type.ime()) // 这里处理键盘显示/隐藏的逻辑 if (imeVisible) { // 键盘显示时的操作 } else { // 键盘隐藏时的操作 } // 必须返回insets,否则会影响其他View的Insets处理 insets }
替代方案:布局中直接设置fitsSystemWindows
如果不想写代码,也可以在Toolbar和底部导航栏的布局XML里加android:fitsSystemWindows="true",系统会自动给它们添加安全区域的padding:
<androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:fitsSystemWindows="true" android:background="?attr/colorPrimary" /> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNavigation" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:fitsSystemWindows="true" />
这样既可以监听键盘状态,又不会出现布局重叠的问题。
内容的提问来源于stack exchange,提问作者Mohanapriya
相关产品推荐
相关产品推荐

