Home > Enterprise >  Jetpack Compose Discrete Slider is not showing the exact numbers
Jetpack Compose Discrete Slider is not showing the exact numbers

Time:01-20

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())
}

The output: enter image description here

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?

CodePudding user response:

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
    )

enter image description here

CodePudding user response:

That's because you are starting from 1 instead of 0. Please plan the value and the steps accordingly,

@Preview
@Composable
private fun MyUI() {

    var sliderValue by remember {
        mutableStateOf(0)
    }

    Slider(value = sliderValue.toFloat(), onValueChange = { sliderValue_ ->
        sliderValue = sliderValue_.toInt()
    }, onValueChangeFinished = {
        // this is called when the user completed selecting the value
    }, valueRange = 0f..21f, steps = 6
    )

    Text(text = sliderValue.toString())
}
  • Related