5
2

More than 1 year has passed since last update.

Jetpack ComposeのPaddingValues同士を加算する

Last updated at Posted at 2022-12-19

LazyColumn / LazyRow の引数で登場する contentPadding: PaddingValues で複数の PaddingValues を加算したい時のコード例です。

実装

Scaffold(
    topBar = {
        TopAppBar()
    }
) { contentPadding ->
    val layoutDirection = LocalLayoutDirection.current
    LazyColumn(
        contentPadding = PaddingValues(
            top = 16.dp + contentPadding.calculateTopPadding(),
            start = contentPadding.calculateStartPadding(layoutDirection),
            end = contentPadding.calculateEndPadding(layoutDirection),
            bottom = 16.dp + contentPadding.calculateBottomPadding(),
        ),
    ) {
        ...
    }
}

PaddingValues#calculateXXXPadding() で持っている padding を取得できるので、加算したい値をプラスして PaddingValues に新たに渡すことで加算しています。

汎用的にするなら

@Composable
operator fun PaddingValues.plus(other: PaddingValues): PaddingValues {
    val layoutDirection = LocalLayoutDirection.current
    return PaddingValues(
        top = calculateTopPadding() + other.calculateTopPadding(),
        start = calculateStartPadding(layoutDirection) + other.calculateStartPadding(layoutDirection),
        end = calculateEndPadding(layoutDirection) + other.calculateEndPadding(layoutDirection),
        bottom = calculateBottomPadding() + other.calculateBottomPadding(),
    )
}

このような拡張関数を用意しておくと次のように実装することができます。

Scaffold(
    topBar = {
        TopAppBar()
    }
) { contentPadding ->
    LazyColumn(
        contentPadding = contentPadding + PaddingValues(vertical = 16.dp) 
    ) {
        ...
    }
}

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2