在解决这个问题几天失败后,我终于决定回去阅读 android文档。所以我通过在活动的窗口焦点发生变化时启用粘性沉浸模式来解决问题,如下所示:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// I removed the below condition check because I still want to hide System UI even if activity
// loses focus. Such cases include spinner dropdown list is open, dialog box is displayed, etc.
// if(hasFocus)
hideSystemUI();
}
private void hideSystemUI() {
// Enables sticky immersive mode.
// For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE_STICKY.
// Or for "regular immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
// 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
// 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);
}
注意:我启用粘性沉浸模式而不是常规沉浸模式的原因是,在常规沉浸模式下,当用户从下到上手势时,非半透明导航栏将永久显示。但是在粘性沉浸模式下,会临时显示一个半透明的导航栏。
更新:我忘了把这个和问题联系起来。由于onWindowFocusChanged(boolean hasFocus) 即使焦点变化是由片段任务引起的也会被触发,因此无需从片段内部隐藏系统UI。