如何在jetpack compose中隐藏导航栏和状态栏?

Dan*_*fer 16 android android-jetpack-compose

我已经知道Accompanist 库可以更改导航和状态栏的颜色。

目标是完全隐藏它们。

Yas*_*ass 31

SystemUiController有一个用于系统栏可见性的 getter/setter 方法:

val systemUiController: SystemUiController = rememberSystemUiController()

systemUiController.isStatusBarVisible = false // Status bar
systemUiController.isNavigationBarVisible = false // Navigation bar
systemUiController.isSystemBarsVisible = false // Status & Navigation bars
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记添加 -> 实现“com.google.accompanist:accompanist-systemuicontroller:0.28.0” (4认同)
  • 无论如何,要通过这个实现 android 粘性沉浸式体验吗? (3认同)
  • WindowCompat.getInsetsController(window,window.decorView).apply { if (isTrue) systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } (2认同)

小智 5

由于 accompanist-systemuicontroller 已被弃用,这里有另一个解决方案。

使用一次性:

@Composable
fun HideSystemBars() {
    val context = LocalContext.current

    DisposableEffect(Unit) {
        val window = context.findActivity()?.window ?: return@DisposableEffect onDispose {}
        val insetsController = WindowCompat.getInsetsController(window, window.decorView)

        insetsController.apply {
            hide(WindowInsetsCompat.Type.statusBars())
            hide(WindowInsetsCompat.Type.navigationBars())
            systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }

        onDispose {
            insetsController.apply {
                show(WindowInsetsCompat.Type.statusBars())
                show(WindowInsetsCompat.Type.navigationBars())
                systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_DEFAULT
            }
        }
    }
}

fun Context.findActivity(): Activity? {
    var context = this
    while (context is ContextWrapper) {
        if (context is Activity) return context
        context = context.baseContext
    }
    return null
}
Run Code Online (Sandbox Code Playgroud)

或者没有:

val insetsController = WindowCompat.getInsetsController(window, window.decorView)

insetsController.apply {
    hide(WindowInsetsCompat.Type.statusBars())
    hide(WindowInsetsCompat.Type.navigationBars())
    systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
Run Code Online (Sandbox Code Playgroud)