要实现这个功能,我们需要通过监听窗口焦点状态的变化来控制导航栏的可见性。下面是实现的步骤和代码示例:
@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (!hasFocus) { hideNavigationBar(); } else { showNavigationBar(); } }
private void hideNavigationBar() { int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; if (Build.VERSION.SDK_INT >= 16) { uiFlags |= View.SYSTEM_UI_FLAG_FULLSCREEN; }
if (Build.VERSION.SDK_INT >= 19) {
uiFlags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
getWindow().getDecorView().setSystemUiVisibility(uiFlags);
}
private void showNavigationBar() { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE); }
通过以上步骤设置后,当窗口失去焦点时,导航栏会自动隐藏。当窗口获得焦点时,导航栏会自动显示。