首页 > 解决方案 > jetpack compose 中的 fitSystemWindows 对应项

问题描述

我有一个透明的状态/导航栏,当我使用默认布局(顶部/左侧)放置一个撰写元素时,它被放置在状态栏下方。在我用来解决这个问题的 xmlfitsSystemWindows中,如何在 jetpack compose 中获得相同的效果?

标签: androidandroid-jetpack-compose

解决方案


这对我有用,在活动中我有:

  WindowCompat.setDecorFitsSystemWindows(window, false)
  setContent {
      JetpackComposePlaygroundTheme {
         val controller = rememberAndroidSystemUiController()
         CompositionLocalProvider(LocalSystemUiController provides controller) {
            ProvideWindowInsets {
                  ComposeAppPlayground()
            }
         }
      }
  }

然后在撰写应用程序游乐场我有这样的事情:

  Surface {

            var topAppBarSize by remember { mutableStateOf(0) }
            val contentPaddings = LocalWindowInsets.current.systemBars.toPaddingValues(
                top = false,
                additionalTop = with(LocalDensity.current) { topAppBarSize.toDp() }
            )

            Column(modifier = Modifier.navigationBarsPadding().padding(top = contentPaddings.calculateTopPadding())) {
               // content can go here forexample...
               // if you want the content go below status bar 
               //   you can remove the top padding for column 
            }

            InsetAwareTopAppBar(
                title = { Text(stringResource(R.string.home)) },
                backgroundColor = MaterialTheme.colors.surface.copy(alpha = 0.9f),
                modifier = Modifier
                    .fillMaxWidth()
                    .onSizeChanged { topAppBarSize = it.height }
            )
        }
    }

还有我从https://google.github.io/accompanist/insets/中提到的 guid 中找到的 InsetAwareTopAppBar

@Composable
fun InsetAwareTopAppBar(
    title: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    navigationIcon: @Composable (() -> Unit)? = null,
    actions: @Composable RowScope.() -> Unit = {},
    backgroundColor: Color = MaterialTheme.colors.primarySurface,
    contentColor: Color = contentColorFor(backgroundColor),
    elevation: Dp = 4.dp
) {
    Surface(
        color = backgroundColor,
        elevation = elevation,
        modifier = modifier
    ) {
        TopAppBar(
            title = title,
            navigationIcon = navigationIcon,
            actions = actions,
            backgroundColor = Color.Transparent,
            contentColor = contentColor,
            elevation = 0.dp,
            modifier = Modifier
                .statusBarsPadding()
                .navigationBarsPadding(bottom = false)
        )
    }
}



推荐阅读