PhongBM
PhongBM

Reputation: 948

Android Compose - How to remove the space above and below the Switch

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

Upvotes: 6

Views: 2624

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363935

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.

Upvotes: 23

Related Questions