I have implemented a discrete slider like this:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
YourProjectNameTheme(darkTheme = false) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(all = 4.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
MyUI()
}
}
}
}
}
}
@Composable
private fun MyUI() {
var sliderValue by remember {
mutableStateOf(1f)
}
Slider(
value = sliderValue,
onValueChange = { sliderValue_ ->
sliderValue = sliderValue_
},
onValueChangeFinished = {
// this is called when the user completed selecting the value
},
valueRange = 1f..21f,
steps = 6
)
Text(text = sliderValue.toString())
}
I'm expecting exact numbers (like 3, 6, 9, 12, 15, 18) when I tap on the tick marks. But, it is showing the nearest float value. How to fix this?
The steps
attribute if greater than 0, specifies the amounts of discrete values, evenly distributed between across the whole value range.
In you case you have to use valueRange = 0f..21f
Slider(
//...
valueRange = 0f..21f,
steps = 6
)