使用ViewCompat.setOnApplyWindowInsetsListener致Status Bar颜色消失的解决咨询
解决监听键盘高度时状态栏颜色变白的问题
一、修复原代码,保留系统默认Insets处理
你遇到的状态栏颜色变白问题,是因为直接给DecorView设置OnApplyWindowInsetsListener后,覆盖了系统默认的Insets处理逻辑,导致状态栏样式无法正常应用。修改代码让系统继续执行默认处理即可解决:
ViewCompat.setOnApplyWindowInsetsListener(this.getWindow().getDecorView(), (v, insets) -> { int keyboardHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom; // 处理键盘高度逻辑 Log.d("Keyboard height: ", String.valueOf(keyboardHeight)); SharedPreferences preferences = this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); if (keyboardHeight > 0) { bottom.getLayoutParams().height = 0; editor.putInt("keyboard_height", keyboardHeight); } else { bottom.getLayoutParams().height = preferences.getInt("keyboard_height", 500); } editor.apply(); bottom.requestLayout(); // 触发布局刷新,确保高度变化生效 // 让系统继续处理默认Insets逻辑,保留状态栏原有样式 return ViewCompat.onApplyWindowInsets(v, insets); });
核心改动是最后一行:不再直接返回insets,而是调用ViewCompat.onApplyWindowInsets(v, insets),让DecorView执行原本的系统Insets处理,这样状态栏颜色就不会被覆盖。
二、手动重置状态栏颜色(备用方案)
如果上述方法仍未解决问题,可以在处理键盘高度的逻辑中,手动重新设置状态栏颜色:
// 设置状态栏背景色 getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.your_status_bar_color)); // 可选:设置状态栏文字颜色(如需深色文字) View decorView = getWindow().getDecorView(); int systemUiFlags = decorView.getSystemUiVisibility(); // 开启浅色状态栏文字(适用于深色状态栏背景) systemUiFlags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; // 若需恢复深色文字,使用:systemUiFlags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; decorView.setSystemUiVisibility(systemUiFlags);
将这段代码放在键盘高度处理逻辑的末尾,每次键盘状态变化时强制重置状态栏样式即可。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

