@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
hideSystemUI();
}
}
private void hideSystemUI() {
// Enables regular immersive mode.
// For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
// Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN);
}
// Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
为了提供更好的用户体验,您可能还需要实现以下功能:
如需实现状态之间的无缝切换,请将所有界面控件的可见性与系统栏保持同步。当应用进入沉浸模式后,任何界面控件也应随系统栏一起隐藏,然后在系统界面重新出现时也再次显示出来。为此,请实现 View.OnSystemUiVisibilityChangeListener 以接收回调,如响应界面可见性更改中所述。
实现 onWindowFocusChanged()。 如果您获得窗口焦点,则可能需要再次隐藏系统栏。 如果您失去了窗口焦点,例如由于在应用界面上出现对话框或弹出式菜单,您可能需要使用 Handler.postDelayed() 或类似方法取消之前调度的所有待处理“隐藏”操作。
实现用于检测 onSingleTapUp(MotionEvent) 的 GestureDetector,以允许用户通过轻触您的内容手动切换系统栏的可见性。 简单的点击监听器并不是这种情况的最佳解决方案,因为即使用户用手指在屏幕上拖动也会触发此类监听器(假设点击目标会占用整个屏幕)。