Sticky immersive mode disabled after soft keyboard shown

jomalden picture jomalden · Jun 12, 2014 · Viewed 15.8k times · Source

I have an app that needs to be full screen most of the time. I know that if an alert is shown or other window is displayed, over the top of the activity window, full screen is temporarily removed. Unfortunately, when a soft keyboard is shown for an EditText or something, when the user has finished with the keyboard, full screen immersive mode is not restored.

Any idea how this can be achieved?

Answer

r3pwn picture r3pwn · Aug 5, 2014

Taken from this sample app by Google, you need to append this to the end of your activity, before the last end bracket:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    // When the window loses focus (e.g. the action overflow is shown),
    // cancel any pending hide action. When the window gains focus,
    // hide the system UI.
    if (hasFocus) {
        delayedHide(300);
    } else {
        mHideHandler.removeMessages(0);
    }
}

private void hideSystemUI() {
    getWindow().getDecorView().setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_LAYOUT_STABLE | 
        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | 
        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | 
        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | 
        View.SYSTEM_UI_FLAG_FULLSCREEN | 
        View.SYSTEM_UI_FLAG_LOW_PROFILE | 
        View.SYSTEM_UI_FLAG_IMMERSIVE
    );
}

private void showSystemUI() {
    getWindow().getDecorView().setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_LAYOUT_STABLE | 
        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | 
        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    );
}

private final Handler mHideHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        hideSystemUI();
    }
};

private void delayedHide(int delayMillis) {
    mHideHandler.removeMessages(0);
    mHideHandler.sendEmptyMessageDelayed(0, delayMillis);
}

And you should be good. :)