Show Label in Material Slider when user stop to drag [KOTLIN]

Viewed 1362

it's possible to make this?

I'm using com.google.android.material.slider.Slider and I know that setLabelFormatter event allows you to see or modify the label when you're dragging the Material Slider but I want to get the value when user stop to drag to know the current value that Material Slider has

enter image description here

Something like this (without getting pressed to take ss haha lol)

Thank you so much

1 Answers

I looked at the material components Slider source code to see how/when it decides to display its label.

  • there doesn't seem to be any public APIs to allow us to make it show up....
  • it shows up when it receives the touch down event....

I wrote some functions to trick the material slider into thinking that it's being touched, triggering the label to show.

fun Slider.showLabelForever()
{
    // start showing the label immediately
    showLabelUntilNextTouchUp()

    // send a touch event when user stops touching the slider to trigger the
    // label to show up again
    addOnSliderTouchListener(
        object:Slider.OnSliderTouchListener
        {
            override fun onStartTrackingTouch(slider:Slider) = Unit
            override fun onStopTrackingTouch(slider:Slider) = showLabelUntilNextTouchUp()
        }
    )
}

fun Slider.showLabelUntilNextTouchUp()
{
    // sent a touch event to cause the label for the slider to show.
    // a side effect of calling onTouchEvent is that it will cause
    // the slider to change the progress value; we save the original
    // progress value before calling onTouchEvent, then restore the
    // value after calling onTouchEvent.
    val originalValue = value
    onTouchEvent(
        MotionEvent.obtain(0L,0L,MotionEvent.ACTION_DOWN,0f,0f,0)
    )
    value = originalValue
}
Related