Cómo responder a cambios de visibilidad de la IU

En esta lección, se describe cómo registrar un objeto de escucha para que tu app pueda recibir notificaciones sobre los cambios de visibilidad de la IU del sistema. Esto es útil si deseas sincronizar otras partes de tu IU con la opción de ocultar o mostrar las barras del sistema.

Cómo registrar un objeto de escucha

Para recibir notificaciones sobre los cambios de visibilidad de la IU del sistema, registra un View.OnSystemUiVisibilityChangeListener en tu vista. Por lo general, es la vista que usas para controlar la visibilidad de navegación.

Por ejemplo, puedes agregar este código al método onCreate() de tu actividad:

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

En general, te recomendamos que mantengas la IU sincronizada con los cambios en la visibilidad de la barra del sistema. Por ejemplo, puedes usar este objeto de escucha para ocultar y mostrar la barra de acciones en acuerdo con la barra de estado oculta y visible.