Skip to content

Commit

Permalink
Prevent a crash in the slider widget
Browse files Browse the repository at this point in the history
The Slider widget will throw an exception if we try to set a value
which does not respect the current step size, and min and max values.

This can happen accidentally, for example when restoing the app's
state from disk.

To prevent similar crashes in the future, this change ensures that
the value is acceptable, and rounds and clamps it if necessary.
  • Loading branch information
felipeerias authored and svillar committed Dec 11, 2024
1 parent 90ca7d5 commit 71ec70e
Showing 1 changed file with 8 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ private void initialize(Context aContext) {

mSlider = findViewById(R.id.settings_slider);
mSlider.setStepSize(mStepSize);
mSlider.setValue(mInitialValue);
mSlider.setValueFrom(mValueFrom);
mSlider.setValueTo(mValueTo);
mSlider.setValue(adjustValueToSliderRange(mInitialValue));
mSlider.clearOnChangeListeners();
mSlider.addOnChangeListener(mInternalOnChangeListener);

Expand All @@ -81,9 +81,15 @@ public void onValueChange(@NonNull Slider slider, float value, boolean fromUser)
}
};

private float adjustValueToSliderRange(float value) {
// Prevent an exception if the value does not respect the step size, and min and max values.
float roundedValue = Math.round((value - mValueFrom) / mStepSize) * mStepSize + mValueFrom;
return Math.max(mValueFrom, Math.min(mValueTo, roundedValue));
}

public void setValue(float value, boolean doApply) {
mSlider.clearOnChangeListeners();
mSlider.setValue(value);
mSlider.setValue(adjustValueToSliderRange(value));
mSlider.addOnChangeListener(mInternalOnChangeListener);

if (mSliderListener != null && doApply) {
Expand Down

0 comments on commit 71ec70e

Please sign in to comment.