0

I found a solution for material.Slider with one thumb, but i need the same for range slider. I need get min and max values from slider. How i can get values from range slider with bindingAdapter?

Sunbey13
  • 339
  • 4
  • 12

2 Answers2

1

You can use LiveData for it. So, your bindingAdapter is going to look like this.

@BindingAdapter("onChange")
fun bindOnChange(rangeSlider: RangeSlider, onChangeLiveData: MutableLiveData<Float>) {
    rangeSlider.addOnChangeListener(RangeSlider.OnChangeListener { _, value, _ ->
        onChangeLiveData.postValue(value)
    })
}

You can use this as

<com.google.android.material.slider.RangeSlider
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:onChange="@{passYourOnChangeMutableLiveDataHere}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49
0

More general and more useful solution:

Create Function in your ViewModel (or anywhere else really) to be called onChange:

val onValueChanged = fun (minAge: Int, maxAge: Int) {
        //TODO use minAge and maxAge here
    }

Create BindingAdapter that will use lamba and feed parameters to the function above:

@BindingAdapter("onChangeListener")
fun RangeSlider.onChangeListener(function: (Int, Int) -> Unit) {
    addOnChangeListener { rangeSlider, value, fromUser ->
        val firstValue = this.values[0].toInt()
        val secondValue = this.values[1].toInt()
        function(firstValue, secondValue)
    }
}

Bind method from BindingAdapter in your layout with function in ViewModel:

<com.google.android.material.slider.RangeSlider
...
bind:onChangeListener="@{ viewModel.onValueChanged }"
/>
Androidz
  • 261
  • 2
  • 11