2

The Slider in Jetpack Compose allows changing the color of the thumb but not the shape. I'm looking solution to change the shape of the thumb from circle to rectangle as represented in the attached image

enter image description here

I tried to add Slider.kt file to the project as mentioned here but, strangely, when I copy this code to the project I got a lot of errors, see attached screenshot

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Yonibagi
  • 147
  • 10

2 Answers2

3

With M3 androidx.compose.material3.Slider you can use the thumb attribute to use a custom thumb.

You can use a simple Spacer or a Box to obtain a Rectangle:

var sliderPosition by remember { mutableStateOf(0f) }
val interactionSource = MutableInteractionSource()

Column {
    Text(text = sliderPosition.toString())

    Slider(
        modifier = Modifier.semantics { contentDescription = "Localized Description" },
        value = sliderPosition,
        onValueChange = { sliderPosition = it },
        valueRange = 0f..5f,
        steps = 4,
        interactionSource = interactionSource,
        onValueChangeFinished = {
            // launch some business logic update with the state you hold
        },
        thumb = {
            val shape = RectangleShape 
            Spacer(
                modifier = Modifier
                    .size(20.dp)
                    .indication(
                        interactionSource = interactionSource,
                        indication = rememberRipple(
                            bounded = false,
                            radius = 20.dp
                        )
                    )
                    .hoverable(interactionSource = interactionSource)
                    .shadow(if (enabled) 6.dp else 0.dp, shape, clip = false)
                    .background(Red, shape)
            )
        },
    )
}

enter image description here

Note: it requires for material3 at least the version 1.0.0-beta03

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

Here is a source code for Slider composable.

You can copy it to your project, rename, and change the Thumb shape in the SliderThumb composable:

...
.shadow(if (enabled) elevation else 0.dp, CircleShape, clip = false)
.background(colors.thumbColor(enabled).value, CircleShape)
...
Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
bylazy
  • 1,055
  • 1
  • 5
  • 16
  • I edited the question, this solution doesn't helped me and I think that should be an easy way to resolve this – Yonibagi Feb 09 '22 at 08:52
  • 3
    Remove "package androidx.compose.material" from your Slider.kt, if its slill there, agree to all IDE's import suggestions, and everything should work. There is no easier way, thumb shape is hardcoded inside private function. – bylazy Feb 09 '22 at 09:37