2
1

More than 1 year has passed since last update.

Jetpack Composeで親のPaddingを無視してサイズ指定する(ネガティブマージンのようなものを作る)

Last updated at Posted at 2022-07-22

こういうやつ。例えばGridで、基本的には16.dpの余白を左右に取るが、トップの画像だけは余白を無視したい、みたいな場合。
image.png

解決策

Modifier.layoutで調整する。拡張関数を作っておくと良さそう。

fun Modifier.extraWidth(width: Dp) = this.layout { measurable, constraints ->
    val placeable = measurable.measure(
        constraints.copy(
            maxWidth = constraints.maxWidth + width.roundToPx() * 2,
        ),
    )
    layout(placeable.width, placeable.height) {
        placeable.place(0, 0)
    }
}

コード例

LazyVerticalGrid(
    columns = GridCells.Fixed(2),
    contentPadding = PaddingValues(16.dp),
    verticalArrangement = Arrangement.spacedBy(24.dp),
    horizontalArrangement = Arrangement.spacedBy(24.dp),
) {
    item(span = { GridItemSpan(2) }) {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .height(256.dp)
                .extraWidth(16.dp) // ここ
                .fillMaxWidth()
                .background(Color.Cyan),
        ) {
            Text("TOP IMAGE")
        }
        Spacer(Modifier.height(16.dp))
    }

    item { Box(Modifier.size(128.dp).background(Color.Gray)) }
    item { Box(Modifier.size(128.dp).background(Color.Gray)) }
    item { Box(Modifier.size(128.dp).background(Color.Gray)) }
    item { Box(Modifier.size(128.dp).background(Color.Gray)) }
}

もっと賢い方法があったら教えて下さい

2
1
2

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
2
1