WindowInsetsControllerCompat隐藏SystemBar后软键盘弹出无法隐藏的替代方案
解决软键盘弹出后系统栏无法隐藏的问题(替代废弃的
setOnSystemUiVisibilityChangeListener) 针对你遇到的软键盘弹出后系统栏无法自动隐藏的问题,以下是两种官方推荐的替代方案,替代已废弃的setOnSystemUiVisibilityChangeListener:
方案一:使用View.setOnApplyWindowInsetsListener监听窗口内边距变化
这是官方指定的setOnSystemUiVisibilityChangeListener替代API,可监听所有窗口内边距(包括系统栏、软键盘)的变化事件:
getWindow().getDecorView().setOnApplyWindowInsetsListener((view, insets) -> { // 检测系统栏是否处于可见状态 boolean systemBarsVisible = insets.isVisible(WindowInsetsCompat.Type.systemBars()); if (systemBarsVisible) { WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(getWindow(), view); insetsController.setSystemBarsBehavior(WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE); insetsController.hide(WindowInsetsCompat.Type.systemBars()); } // 返回处理后的Insets,保证其他布局逻辑正常执行 return view.onApplyWindowInsets(insets); });
原理:当软键盘弹出导致系统栏重新显示时,该监听会被触发,此时我们重新执行系统栏隐藏逻辑,覆盖系统的默认行为。
方案二:监听软键盘收起事件,主动触发隐藏逻辑
通过布局高度变化判断软键盘状态,在软键盘收起后主动调用你的hideSystemBar()方法:
View decorView = getWindow().getDecorView(); decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { private int lastVisibleHeight = 0; @Override public void onGlobalLayout() { Rect visibleFrame = new Rect(); decorView.getWindowVisibleDisplayFrame(visibleFrame); int currentVisibleHeight = visibleFrame.bottom - visibleFrame.top; // 当可见高度从低变高,说明软键盘已收起 if (lastVisibleHeight != 0 && currentVisibleHeight > lastVisibleHeight) { hideSystemBar(); } lastVisibleHeight = currentVisibleHeight; // 移除监听避免内存泄漏(适配不同Android版本) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { decorView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { decorView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } } });
额外优化建议:
确保你的Activity主题配置了全屏相关属性,减少系统栏自动显示的触发概率:
<!-- 在styles.xml的Activity主题中添加 --> <item name="android:windowFullscreen">true</item> <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item> <!-- 适配刘海屏设备 -->
内容的提问来源于stack exchange,提问作者SwitchDestiny
相关产品推荐
相关产品推荐

