1

I have Row with two components, Text and Switch, after adding the Switch, I see the space above and below. I want the heigh of Switch is fit to UI height.

I use padding(0.dp) but it is not working.

How to remove that?

This is my code:

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(color = Color.Red),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = "This is a text",
            modifier = Modifier.background(color = Color.Yellow)
        )
        Switch(
            checked = false,
            onCheckedChange = {},
            modifier = Modifier
                .padding(0.dp)
                .background(color = Color.Blue)
        )
    }

Screenshot

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
PhongBM
  • 799
  • 10
  • 23

1 Answers1

6

The Switch as many other components has a minimum touch target size (48.dp) for accessibility. It is applied with the minimumInteractiveComponentSize modifier.It will include extra space outside the component to ensure that they are accessible.

You can check in the doc:

Reserves at least 48.dp in size to disambiguate touch interactions if the element would measure smaller. https://m2.material.io/design/usability/accessibility.html#layout-and-typography

This uses the Material recommended minimum size of 48.dp x 48.dp, which may not the same as the system enforced minimum size. The minimum clickable / touch target size (48.dp by default) is controlled by the system via ViewConfiguration and automatically expanded at the touch input layer.

You can override this behaviour applying false to the LocalMinimumInteractiveComponentEnforcement. If it is set to false there will be no extra space.

CompositionLocalProvider(LocalMinimumInteractiveComponentEnforcement provides false) {

        Switch(
            checked = switchState,
            onCheckedChange = { switchState = !switchState },
            modifier = Modifier
                .padding(0.dp)
                .background(color = Teal200)
        )
    }

enter image description here

Note: LocalMinimumInteractiveComponentEnforcement requires at least M2 1.4.0-alpha04 and M3 1.1.0-alpha04. Before you can use LocalMinimumTouchTargetEnforcement in the same way.

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