如何隐藏 Android 11 应用中的状态栏?

Rud*_*ina 7 android kotlin android-statusbar android-api-levels android-11

我遇到的所有隐藏 Android 应用状态栏的方法在 Android 11 中均已弃用。

有谁知道目前可以接受的方法吗?

我还使用 Kotlin 来开发我的应用程序。

hat*_*ata 22

当您的设备是 API-30(Android 11;minSdkVersion 30)或更高版本时,setSystemUiVisibility已弃用,您可以使用新引入的版本WindowInsetsController。(请注意,您不能WindowInsetsController在 API-29 或更早版本上使用)。

所以官方参考说:

此方法在 API 级别 30 中已弃用。SystemUiVisibility 标志已弃用。WindowInsetsController代替使用。

你应该使用WindowInsetsController类。

在科特林中:

window.decorView.windowInsetsController!!.hide(
    android.view.WindowInsets.Type.statusBars()
)
Run Code Online (Sandbox Code Playgroud)

在爪哇中:

getWindow().getDecorView().getWindowInsetsController().hide(
    android.view.WindowInsets.Type.statusBars()
);
Run Code Online (Sandbox Code Playgroud)

如果您还想隐藏导航栏:

在科特林中:

window.decorView.windowInsetsController!!.hide(
    android.view.WindowInsets.Type.statusBars()
            or android.view.WindowInsets.Type.navigationBars()
)
Run Code Online (Sandbox Code Playgroud)

在爪哇中:

getWindow().getDecorView().getWindowInsetsController().hide(
    android.view.WindowInsets.Type.statusBars()
            | android.view.WindowInsets.Type.navigationBars()
);
Run Code Online (Sandbox Code Playgroud)


Slo*_*ing 9

API 级别 < 16

如果您想在应用程序中隐藏,status bar只需将应用程序设置为全屏即可。在你的onCreate方法中只需添加FLAG_FULLSCREEN

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_loading);
Run Code Online (Sandbox Code Playgroud)

这就是如果Build.VERSION.SDK_INT < 16

API 级别 >= 16 且 < 30

这适用于Build.VERSION.SDK_INT大于 16 的情况;

    View decorView = getWindow().getDecorView();
    // Hide the status bar.
    int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
    decorView.setSystemUiVisibility(uiOptions);
Run Code Online (Sandbox Code Playgroud)

只需将其添加到onCreate您想要隐藏status bar. 您可以在这里阅读更多内容:https ://developer.android.com/training/system-ui/status#41


编辑:API 级别 >= 30

SYSTEM_UI_FLAG_FULLSCREEN即使文档中没有说明,Android 11 似乎也对此进行了贬低。但根据本教程,您可以在 Android 11 中执行此操作,您需要使用WindowInsetsController及其hide()方法。就像建议的其他答案一样,您可以使用:

getWindow().getDecorView().getWindowInsetsController().hide(
        android.view.WindowInsets.Type.statusBars()
    );
Run Code Online (Sandbox Code Playgroud)

所以,这适用于Android 11及更高版本,其他方法适用于早期版本。