响应界面可见性变化

本课介绍了如何注册监听器,以便你的应用在系统界面可见性发生变化时收到通知。如果你想让应用界面的其他部分与系统栏的隐藏/显示同步,这将非常有用。

注册监听器

要在系统界面可见性发生变化时收到通知,请向你的视图注册一个 View.OnSystemUiVisibilityChangeListener。这通常是你用于控制导航可见性的视图。

例如,你可以将此代码添加到 Activity 的 onCreate() 方法中

Kotlin

window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
    // Note that system bars will only be "visible" if none of the
    // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
    if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
        // TODO: The system bars are visible. Make any desired
        // adjustments to your UI, such as showing the action bar or
        // other navigational controls.
    } else {
        // TODO: The system bars are NOT visible. Make any desired
        // adjustments to your UI, such as hiding the action bar or
        // other navigational controls.
    }
}

Java

View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener
        (new View.OnSystemUiVisibilityChangeListener() {
    @Override
    public void onSystemUiVisibilityChange(int visibility) {
        // Note that system bars will only be "visible" if none of the
        // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
        if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
            // TODO: The system bars are visible. Make any desired
            // adjustments to your UI, such as showing the action bar or
            // other navigational controls.
        } else {
            // TODO: The system bars are NOT visible. Make any desired
            // adjustments to your UI, such as hiding the action bar or
            // other navigational controls.
        }
    }
});

通常,最好让界面与系统栏可见性的变化保持同步。例如,你可以使用此监听器,使操作栏与状态栏的隐藏和显示同步进行隐藏和显示。