對 UI 顯示設定變更的回應

本課程將說明如何註冊事件監聽器,讓應用程式在系統 UI 瀏覽權限變更時通知應用程式。如果您想將 UI 的其他部分與隱藏/顯示系統資訊列同步處理,這個方法就非常實用。

註冊事件監聽器

如要接收系統 UI 瀏覽權限變更通知,請在檢視畫面中註冊 View.OnSystemUiVisibilityChangeListener。一般來說,您可以使用的檢視畫面控制導覽瀏覽權限。

舉例來說,您可以將這段程式碼新增至活動的 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.
        }
    }
});

一般而言,最佳做法是讓 UI 與系統列顯示設定的變更保持同步。舉例來說,您可以利用這個事件監聽器,在憑證中隱藏和顯示動作列,同時將狀態列隱藏和顯示。