Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An alternative solution to set negative padding values in Jetpack Compose? (java.lang.IllegalArgumentException: Padding must be non-negative)

I'm trying to assign a negative value to the padding modifier but the app had crashed. Have a look at my code. Thanks if you can help or give me an alternative solution

In my example, I assign Modifier.padding(horizontal = 16.dp)to parent compose (LazyColum). But I want the first child (Image) to be Modifier.padding(horizontal = -16.dp) to fill the full width of the screen. Instead, I had to assign each padding value to each child.

Crash log: java.lang.IllegalArgumentException: Padding must be non-negative

enter image description here

Code snippet

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
    
}
like image 260
Wilson Tran Avatar asked Feb 28 '21 10:02

Wilson Tran


1 Answers

The padding modifier doesn't support negative values, but you can use the offset modifier instead:

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

That being said, I'd prefer using a Column with the image and a LazyColumn with the content (and applied padding) here instead.

Column {
    Image(...)
    LazyColumn(Modifier.padding(16.dp)) {
        ... all content here
    }
}
like image 154
jossiwolf Avatar answered Sep 30 '22 11:09

jossiwolf