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?
Asked
Active
Viewed 218 times
2 Answers
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
-
please, can you share the example of liveData for RangeSlider (it must have 2 values min/max)? – Sunbey13 Aug 16 '21 at 10:12
-
your suggestion works, but livedata only gets one value (last changed) when I need a range (from X to Y) – Sunbey13 Aug 16 '21 at 10:36
-
@user14729932 sorry I don't follow? Do you want the previous and the changed value? – OhhhThatVarun Aug 16 '21 at 10:45
-
1i have corrected your answer to be the way it should work. Thanks, your suggestion helped to solve my problem. – Sunbey13 Aug 16 '21 at 10:56
-
@user14729932 i saw your edit. What would I suggest you is to use a `Pair` instead of a `List`. – OhhhThatVarun Aug 16 '21 at 11:27
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