ViewCompat.setOnApplyWindowInsetsListener使状态栏颜色消失

问题描述 投票:0回答:2

这是我用来检测

Keyboard Height
何时发生变化的代码。

唯一的问题是,当此代码运行时,

Statur Bar
颜色消失并变成白色。

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;
});

有任何不改变

Status Bar
颜色的替代代码吗?

或者在此代码运行后以编程方式重新添加

Status Bar
颜色的任何方法?

java android statusbar android-statusbar android-window
2个回答
4
投票

您可以通过返回

WindowInsetsCompat.CONSUMED
而不是
insets

来消费 insets 调度事件来解决此问题

根据文档

这可以在视图层次结构中的 insets 分派期间使用,通过从 View.onApplyWindowInsets(WindowInsets) 或 onApplyWindowInsets 返回此值来停止将 insets 分派到其子级,以避免遍历整个视图层次结构。

应用程序应该在处理完视图层次结构中某个级别上的所有插图后返回此实例,并且不需要再分派给其子级以获得更好的性能。

更新:

这确实有效,似乎只是将操作栏推到屏幕顶部,使操作栏比平常更高。但我想我可以在操作栏的顶部添加一些高度和填充来防止这种情况发生。

嗯,这似乎确实使 Activity 全屏显示,甚至还与导航栏相交。

现在要修复该问题,请返回以下内容:

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);
    });

0
投票

作为@Zain的回答的结论:

ViewCompat.setOnApplyWindowInsetsListener(activity.window.decorView) { view, insets ->
    // do the job
    ViewCompat.onApplyWindowInsets(view, insets)
}
© www.soinside.com 2019 - 2024. All rights reserved.