Phil Dukhov
Phil Dukhov

Reputation: 87904

fitsSystemWindows counterpart in jetpack compose

I have a transparent status/navigation bars, and when I place a compose element with default layout(top/left), it's placed under the status bar. In xml I use fitsSystemWindows to fix this, how can I get same effect in jetpack compose?

Upvotes: 11

Views: 11066

Answers (1)

Mateo Vakili
Mateo Vakili

Reputation: 712

This works for me, In Activity I have :

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

Then In compose app playground I have something like this:

  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 }
            )
        }
    }

Also the InsetAwareTopAppBar I found from guids mentioned in https://google.github.io/accompanist/insets/

@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)
        )
    }
}


Upvotes: 2

Related Questions