Jetpack Compose中设置负边距值的替代解决方案?(java.lang.IllegalArgumentException: Padding must be non-negative)

28

我尝试将padding修饰符赋值为负值,但应用程序崩溃了。请看一下我的代码。如果您可以帮助或提供替代解决方案,谢谢。

在我的示例中,我将Modifier.padding(horizontal = 16.dp)分配给父组合(LazyColum)。但是我希望第一个子项(Image)为Modifier.padding(horizontal = -16.dp)以填充屏幕的全部宽度。但是,我必须为每个子项分配每个padding值。

崩溃日志:java.lang.IllegalArgumentException: Padding must be non-negative

enter image description here

代码片段:

LazyColumn(modifier = Modifier.padding(16.dp), state = lazyListState) {
    item {
        Image(
            modifier = Modifier
                .fillMaxWidth()
                .padding(-16.dp) // Crashed here!
                .height(200.dp),
            painter = painterResource(id = puppy.artwork),
            contentDescription = "Puppy ArtWork",
            contentScale = ContentScale.Crop
        )
    }
    item {
        Row(
            modifier = Modifier
                .padding(horizontal = 16.dp)
                .padding(top = 16.dp)
        ) {
            Text(text = puppy.name, style = MaterialTheme.typography.h4)
            Spacer(modifier = Modifier.weight(1f))
            Price(puppy.pricePerHour)
        }
    }
    item {
        CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
            Text(
                modifier = Modifier.padding(top = 16.dp)
                text = puppy.about
            )
        }
    }
    item {
        PuppyInfo(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp),
            puppy = puppy
        )
    }
    .... // A lot of children here
    
}
3个回答

61

填充修改器不支持负值,但您可以使用offset 修改器:

val columnPadding = 16.dp
LazyColumn(modifier = Modifier.padding(columnPadding), state = lazyListState) {
    item {
        Image(
            modifier = Modifier
                .fillMaxWidth()
                .offset(x = -columnPadding)
                .height(200.dp),
            ...
        )
    }
    ...

话虽如此,我宁愿在这里使用一个带有图像的Column和一个带有内容(以及应用的填充)的LazyColumn

Column {
    Image(...)
    LazyColumn(Modifier.padding(16.dp)) {
        ... all content here
    }
}

1
我刚刚尝试了你提供的两种解决方案,但对我来说都不起作用!感谢你的帮助。 - Wilson Tran
2
我需要比那更多的信息 :) - jossiwolf

9
如果要增加宽度且在水平方向上对齐,可以使用layout()修饰符。我编写了一个修饰符扩展函数,可用于忽略父级填充。
fun Modifier.ignoreHorizontalParentPadding(horizontal: Dp): Modifier {
    return this.layout { measurable, constraints ->
        val overridenWidth = constraints.maxWidth + 2 * horizontal.roundToPx()
        val placeable = measurable.measure(constraints.copy(maxWidth = overridenWidth))
        layout(placeable.width, placeable.height) {
            placeable.place(0, 0)
        }
    }
}

0
只需使用requiredWidth()来给出Box()的绝对宽度。如果需要的话,还可以添加padding。
Box(
    modifier = Modifier
        .requiredWidth(LocalConfiguration.current.screenWidthDp.dp)
        .padding(horizontal = 8.dp)
){
    //...
}

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接