How to increase the track height of a slider in material design 3

1.9k views Asked by At
@Composable
fun SliderWithCustomTrackAndThumb() {
    var sliderPosition by remember { mutableStateOf(0f) }
    val interactionSource = MutableInteractionSource()
    val colors = SliderDefaults.colors(thumbColor = Color.Red, activeTrackColor = Color.Red)
    Column {
        Text(text = sliderPosition.toString())
        Slider(
            modifier = Modifier.semantics { contentDescription = "Localized Description" },
            value = sliderPosition,
            onValueChange = { sliderPosition = it },
            valueRange = 0f..100f,
            onValueChangeFinished = {
                // launch some business logic update with the state you hold
                // viewModel.updateSelectedSliderValue(sliderPosition)
            },
            interactionSource = interactionSource,
            thumb = {
                SliderDefaults.Thumb(
                    interactionSource = interactionSource,
                    colors = colors
                )
            },
            track = { sliderPositions ->
                SliderDefaults.Track(
                    colors = colors,
                    sliderPositions = sliderPositions
                )
            }
        )
    }
}

The above composable function creates a sample slider with a custom thumb size. I want to increase the size of the track. how can I do that?

2

There are 2 answers

0
Mirhack On

You can increase or decrease the size of the track and thumb using scale modifiers. This is how I do it:

@Composable
private fun Slider() {
    val interactionSource = remember { MutableInteractionSource() }
    Slider(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp),
        value = 0.5f,
        interactionSource = interactionSource,
        onValueChange = { value: Float -> },
        valueRange = 0f..1f,
        track = { sliderPositions ->
            SliderDefaults.Track(
                modifier = Modifier.scale(scaleX = 1f, scaleY = 0.5f),
                sliderPositions = sliderPositions
            )
        },
        thumb = {
            SliderDefaults.Thumb(
                modifier = Modifier.scale(scaleX = 0.5f, scaleY = 0.5f),
                interactionSource = interactionSource,
            )
        }
    )
}   

screenshot

0
Jack On

while you can't change the size size of the track set in the SlideDefaults.Track()component, you can always provide your own track implementation by copying the code from the SliderDefaults and change the track size there.