ViewCompat.setOnApplyWindowInsetsListener 会使状态栏颜色消失。

4

这是我用来检测键盘高度变化的代码。

问题只在于当此代码运行时,状态栏颜色会消失并变为白色。

ViewCompat.setOnApplyWindowInsetsListener(this.getWindow().getDecorView(), (v, insets) -> {

        int keyboardHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom;

        //Do your job here
        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();

        return insets;
});

有没有其他的代码可以不改变 状态栏 的颜色?

或者有没有办法在这段代码运行后以编程方式重新添加 状态栏 的颜色?

1个回答

4
您可以通过返回WindowInsetsCompat.CONSUMED而不是insets来消耗嵌入式分发事件来解决此问题。 按照文档说明
这可以在视图层次结构中的插图派遣期间使用,通过从View.onApplyWindowInsets(WindowInsets)或onApplyWindowInsets返回此值来停止将插图派送到其子级以避免遍历整个视图层次结构。 应用程序应该在处理视图层次结构中某个级别上的所有插图后返回此实例,并且不需要再将其分派给其子级以获得更好的性能。 更新: 这确实有效,似乎只是将操作栏推到屏幕顶部,使操作栏比通常更高。但我想我可以添加一些高度和填充到操作栏的顶部来防止这种情况。
那确实让活动全屏了,甚至与导航栏相交。
现在要修复它,请返回以下内容:
ViewCompat.onApplyWindowInsets(v, insets)

ViewCompat.setOnApplyWindowInsetsListener(this.getWindow().getDecorView(), (v, insets) -> {

        int keyboardHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom;

        //Do your job here
        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();

        return ViewCompat.onApplyWindowInsets(v, insets);
    });

这个是有效的,看起来只是把操作栏推到了屏幕顶部,使操作栏比通常更高了。但我想我可以在操作栏顶部添加一些高度和填充来防止这种情况发生。 - Peter
太棒了!非常好用,不过我确实需要删除“!!”,我不知道它们为什么会在那里。 - Peter
1
抱歉,我在 Kotlin 中进行测试,忘记删除了。祝你编码愉快 :) - Zain
返回 WindowInsetsCompat.CONSUMED 会导致一些不希望的 UI 变化,正如所提到的那样。而返回 ViewCompat.onApplyWindowInsets(v, insets) 则有效。谢谢! - Bruce

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接