8

Expectation

enter image description here

Reality

enter image description here

(Please ignore the exact colours; Outer background colour is purple and inner background colour is red)

Compose code

@Preview
@Composable
fun MyCta() {
    MaterialTheme() {
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(50))
                .padding(32.dp)
                .background(MaterialTheme.colors.primary)
        ) {
            Text(
                "Tap to continue",
                Modifier
                    .padding(8.dp)
                    .background(Color.Red)
                ,
                color = MaterialTheme.colors.onPrimary
            )
        }
    }
}

Is my expectation off and why?

ericn
  • 12,476
  • 16
  • 84
  • 127

2 Answers2

9

You want to use the padding after you have specified the background

@Preview
@Composable
fun MyCta() {
    MaterialTheme() {
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(50))
                .background(MaterialTheme.colors.primary)
                .padding(32.dp)
        ) {
            Text(
                "Tap to continue",
                Modifier
                    .padding(8.dp)
                    .background(Color.Red)
                ,
                color = MaterialTheme.colors.onPrimary
            )
        }
    }
}

Note: The explicit order helps you to reason about how different
modifiers will interact. Compare this to the view-based system where
you had to learn the box model, that margins applied "outside" the
element but padding "inside" it, and a background element would be
sized accordingly. The modifier design makes this kind of behavior
explicit and predictable, and gives you more control to achieve the
exact behavior you want.

Modifiers documentation:

RaBaKa 78
  • 1,115
  • 7
  • 11
3

Use

Box(
    modifier = Modifier
        .background(MaterialTheme.colors.primary,
            RoundedCornerShape(50))
        .padding(32.dp)
)

You have to apply the padding modifier after the background.
It is important the order of modifiers.

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841