Responder a alterações de visibilidade da IU

Esta lição descreve como registrar um listener para que seu app possa ser notificado sobre alterações na visibilidade da IU do sistema. Isso é útil para sincronizar outras partes da sua IU com a ocultação/exibição de barras do sistema.

Registrar um listener

Para receber notificações sobre alterações na visibilidade da IU do sistema, registre um View.OnSystemUiVisibilityChangeListener na sua visualização. Geralmente, essa é a visualização que você está usando para controlar a visibilidade da navegação.

Por exemplo, você pode adicionar este código ao método onCreate() da sua atividade:

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

Em geral, recomenda-se manter sua IU sincronizada com as alterações na visibilidade da barra do sistema. Por exemplo, você pode usar esse listener para ocultar e mostrar a barra de ação em conjunto com a barra de status.