简体   繁体   中英

Jetpack Compose Change Slider Thumb Size

Is there any way to change slider thumb size? I think for now we can only manipulate colors

var sliderPosition by remember { mutableStateOf(0f) }
Text(text = sliderPosition.toString())
Slider(
    value = sliderPosition,
    onValueChange = { sliderPosition = it },
    valueRange = 0f..100f,
    onValueChangeFinished = {
        // launch some business logic update with the state you hold
        // viewModel.updateSelectedSliderValue(sliderPosition)
    },
    steps = 5,
    colors = SliderDefaults.colors(
        thumbColor = MaterialTheme.colors.secondary,
        activeTrackColor = MaterialTheme.colors.secondary
    )
)

Jetpack-Compose 滑块

No, this size cannot be modified. The only thing you can do is copy the entire Slider.kt file into your project and modify it.

It is a good idea to give the new view a different name to avoid misunderstandings in the future.

You should change ThumbRadius constant, or make it a variable if you need different sizes in your application.

Yes, but only wrapping it with AndroidView and wait for the better future, when Google team release another update in Material lib.

Here is an example

  AndroidView(
    modifier = Modifier...//,
    factory = { context ->
      Slider(
        ContextThemeWrapper(context, context.theme)
      ).apply {
      // set listeners
      it.addOnSliderTouchListener(object : SliderView.OnSliderTouchListener {
        @SuppressLint("RestrictedApi")
        override fun onStartTrackingTouch(slider: Slider) = Unit

        @SuppressLint("RestrictedApi")
        override fun onStopTrackingTouch(slider: Slider) {
          onValueChangeFinished.invoke()
        }
      })
      it.addOnChangeListener { _, value, _ ->
        onValueChanged.invoke(value)
      }
        // your thumb customization
        // your track customization
      }
  }, update = {
      // set value
      it.value = currentValue
  })

Should be placed inside @Composable

I've created a library for easy customization of Slider, since Slider from Material package is not flexible. https://github.com/krottv/compose-sliders . Below is the code example of how to use it to make thumb size smaller:

var stateSlider by remember { mutableStateOf(0.5f) }
SliderValueHorizontal(
    stateSlider, { stateSlider = it },
    modifier = Modifier
        .fillMaxWidth(),
    // desired size of Slider's thumb
    thumbSize = DpSize(8.dp, 8.dp)
)

Also you can specify custom composables for thumb and track.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM