如果你在开发中使用了 Android 12,你可能会遇到一个问题,即导航栏消失,导致你的应用程序显示异常。这是由于 Android 12 中引入了全新的沉浸式模式,导致导航栏在应用程序打开时会自动隐藏。如果你想要恢复正常的导航栏,你可以在代码中进行如下设置:
在 Activity 或 Fragment 中添加以下代码:
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Show the navigation bar and status bar.
window.insetsController?.show(WindowInsets.Type.navigationBars() or WindowInsets.Type.statusBars())
}
}
这段代码会在应用程序获得焦点时检查系统版本,如果系统版本为 Android 12 或更高版本,则会将导航栏和状态栏显示出来。
如果你使用的是 Java,则可以使用以下代码:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Show the navigation bar and status bar.
WindowInsetsController controller = getWindow().getInsetsController();
if (controller != null) {
controller.show(WindowInsets.Type.navigationBars()
| WindowInsets.Type.statusBars());
}
}
}
在这种情况下,如果应用程序版本为 Android 12 或更高版本,则会显示导航栏和状态栏。
当然,如果你的应用程序没有必要使用沉浸式模式,你也可以在应用程序主题中禁用它,方法如下: