Skip to content

Commit ec7f7cb

Browse files
cketchamdsn5ft
authored andcommitted
[Slider] Adds a warning message if the stepSize or any values are set to float values with a decimal to suggest using integers.
PiperOrigin-RevId: 327685433 (cherry picked from commit 7e37eaa)
1 parent 8059ac1 commit ec7f7cb

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

lib/java/com/google/android/material/slider/BaseSlider.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.RangeInfoCompat;
5353
import androidx.appcompat.content.res.AppCompatResources;
5454
import android.util.AttributeSet;
55+
import android.util.Log;
5556
import android.view.KeyEvent;
5657
import android.view.MotionEvent;
5758
import android.view.View;
@@ -193,6 +194,10 @@ abstract class BaseSlider<
193194
"valueTo(%s) must be greater than valueFrom(%s)";
194195
private static final String EXCEPTION_ILLEGAL_STEP_SIZE =
195196
"The stepSize(%s) must be 0, or a factor of the valueFrom(%s)-valueTo(%s) range";
197+
private static final String WARNING_FLOATING_POINT_ERRROR =
198+
"Floating point value used for %s(%s). Using floats can have rounding errors which may"
199+
+ " result in incorrect values. Instead, consider using integers with a custom"
200+
+ " LabelFormatter to display the value correctly.";
196201

197202
private static final int TIMEOUT_SEND_ACCESSIBILITY_EVENT = 200;
198203
private static final int HALO_ALPHA = 63;
@@ -504,12 +509,32 @@ private void validateValues() {
504509
}
505510
}
506511

512+
private void warnAboutFloatingPointError() {
513+
if (stepSize == 0) {
514+
// Only warn if slider uses a step value.
515+
return;
516+
}
517+
518+
if ((int) stepSize != stepSize) {
519+
Log.w(TAG, String.format(WARNING_FLOATING_POINT_ERRROR, "stepSize", stepSize));
520+
}
521+
522+
if ((int) valueFrom != valueFrom) {
523+
Log.w(TAG, String.format(WARNING_FLOATING_POINT_ERRROR, "valueFrom", valueFrom));
524+
}
525+
526+
if ((int) valueTo != valueTo) {
527+
Log.w(TAG, String.format(WARNING_FLOATING_POINT_ERRROR, "valueTo", valueTo));
528+
}
529+
}
530+
507531
private void validateConfigurationIfDirty() {
508532
if (dirtyConfig) {
509533
validateValueFrom();
510534
validateValueTo();
511535
validateStepSize();
512536
validateValues();
537+
warnAboutFloatingPointError();
513538
dirtyConfig = false;
514539
}
515540
}

0 commit comments

Comments
 (0)