Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Databinding and LiveData for RangeSlider (valueFrom and valueTo)

I have the following RangeSlider and I am using DataBinding to provide the minimum / maximum value of the slider, as it may change while the user is on the screen.

RangeSlider

layout.xml

<layout ...>
    <data>

        <variable
            name="item"
            type="MyDataItem" />
    </data>

    ...

        <com.google.android.material.slider.RangeSlider
            android:id="@+id/my_slider"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:stepSize="1"
            android:valueFrom="@{item.minimum}"
            android:valueTo="@{item.maximum}"
            ... />
</layout>

MyDataItem:

data class MyDataItem() {
    val minimum = MutableLiveData(Int.MIN_VALUE)
    val maximum = MutableLiveData(Int.MAX_VALUE)
}

However, whenever the app tries to inflate the view I get java.lang.IllegalStateException: valueFrom(0.0) must be smaller than valueTo(0.0)

like image 782
Sampson Avatar asked Oct 30 '25 05:10

Sampson


1 Answers

Here is a complete solution how to implement two-way databinding with RangeSlider

ViewModel/Presenter:

var sliderRange = MutableLiveData<List<Float>>().apply { value = listOf(5f, 90f) }

Put there your initial data

Then, layout:

<com.google.android.material.slider.RangeSlider
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stepSize="1"
    android:valueFrom="1"
    android:valueTo="100"
    app:values="@={vm.sliderRange}" />

And finally how to put things together; BindingAdapter with InverseBindingAdapter :

@InverseBindingAdapter(attribute = "values")
fun getRangeSlider(slider: RangeSlider): List<Float> {
    return slider.values
}

@BindingAdapter("app:valuesAttrChanged")
fun setListeners(
    slider: RangeSlider,
    attrChange: InverseBindingListener
) {
    val listener = RangeSlider.OnChangeListener { _, _, _ -> attrChange.onChange() }
    slider.addOnChangeListener(listener)
}

Good luck,'.

like image 154
Maher Abuthraa Avatar answered Oct 31 '25 21:10

Maher Abuthraa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!