在Android API 30及以下版本中,隐藏系统导航栏的代码如下:
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
但在API 31中,该方法已被标记为过时(deprecated)。而新的方法如下:
WindowInsetsController insetsController = ViewCompat.getWindowInsetsController(getWindow().getDecorView());
if (insetsController != null) {
insetsController.hide(WindowInsetsCompat.Type.navigationBars());
}
这将使用新的WindowInsets API替换旧的System UI Visibility API。同时,获得WindowInsetsController需要使用ViewCompat.getWindowInsetsController(),而不是直接使用View.getWindowInsetsController()。
需要注意的是,为了使此方法在所有版本的Android上兼容,需添加以下依赖项:
implementation 'androidx.core:core-ktx:1.7.0'
这样就可以在Android API 31及以上版本上成功隐藏系统导航栏。