Hello all, Is there anyway to add label below each...
# compose
s
Hello all, Is there anyway to add label below each steps in Slider?. Currently I’m using Range slider in Jetpack compose. I want to achieve this behaviour 👇
n
You can do this:
Copy code
@Composable
fun MySlider() {
    val maxValue = 5
    var value by remember { mutableStateOf(0f) }
    Column(
        Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Slider(value = value, onValueChange = { value = it })
        Row(
            Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            for (i in 0..maxValue) {
                Text(i.toString())
            }
        }
    }
}
r
In general I don't know how you would get those labels to line up. For example, modify your example to be a discrete
Slider
(e.g., add
steps = 3, valueRange = 0f..4f
) and the labels will not line up with the tick marks.
s
@nglauber Thanks for this. It works. I’ve made small change in above code 👇
Copy code
@Composable
fun MySlider() {
    var sliderState by remember { mutableStateOf(0F) }
    val maxValue by remember { mutableStateOf(5) }
    
    Column(
        Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text(
            text = makeValueRound(sliderState).toString(),
            style = typography.subtitle1,
            color = colors.onPrimary
        )
        Slider(
            value = sliderState,
            onValueChange = { sliderState = it },
            valueRange = 0f..4f,
            steps = 4
        )
        Row(
            Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            for (i in 0..maxValue) {
                Text(
                    i.toString(),
                    style = typography.subtitle1,
                    textAlign = TextAlign.Center,
                    color = colors.onPrimary
                )
            }
        }
    }
}
Here's the result 👇
Added this function to make values round 😅. Otherwise it’s going to give
2.4
when we select
3
.
Copy code
fun makeValueRound(value:Float):Float{
    return when(value){
        0.0F -> 0.0F
        0.8F -> 1.0F
        1.6F -> 2.0F
        2.4F -> 3.0F
        3.2F -> 4.0F
        4.0F -> 5.0F
        else -> 0.0F
    }
}
👍 1
r
To avoid the need for rounding set
valueRange = 0f..5f
(and keep
steps= 4
), since you have six values, 0-5. (BTW the misalignment I mentioned is more noticeable with more values.)