Skip to content

Commit

Permalink
[Slider] Adds a warning message if the stepSize or any values are set…
Browse files Browse the repository at this point in the history
… to float values with a decimal to suggest using integers.

PiperOrigin-RevId: 327685433
(cherry picked from commit 7e37eaa)
  • Loading branch information
cketcham authored and dsn5ft committed Aug 28, 2020
1 parent 8059ac1 commit ec7f7cb
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/java/com/google/android/material/slider/BaseSlider.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.RangeInfoCompat;
import androidx.appcompat.content.res.AppCompatResources;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
Expand Down Expand Up @@ -193,6 +194,10 @@ abstract class BaseSlider<
"valueTo(%s) must be greater than valueFrom(%s)";
private static final String EXCEPTION_ILLEGAL_STEP_SIZE =
"The stepSize(%s) must be 0, or a factor of the valueFrom(%s)-valueTo(%s) range";
private static final String WARNING_FLOATING_POINT_ERRROR =
"Floating point value used for %s(%s). Using floats can have rounding errors which may"
+ " result in incorrect values. Instead, consider using integers with a custom"
+ " LabelFormatter to display the value correctly.";

private static final int TIMEOUT_SEND_ACCESSIBILITY_EVENT = 200;
private static final int HALO_ALPHA = 63;
Expand Down Expand Up @@ -504,12 +509,32 @@ private void validateValues() {
}
}

private void warnAboutFloatingPointError() {
if (stepSize == 0) {
// Only warn if slider uses a step value.
return;
}

if ((int) stepSize != stepSize) {
Log.w(TAG, String.format(WARNING_FLOATING_POINT_ERRROR, "stepSize", stepSize));
}

if ((int) valueFrom != valueFrom) {
Log.w(TAG, String.format(WARNING_FLOATING_POINT_ERRROR, "valueFrom", valueFrom));
}

if ((int) valueTo != valueTo) {
Log.w(TAG, String.format(WARNING_FLOATING_POINT_ERRROR, "valueTo", valueTo));
}
}

private void validateConfigurationIfDirty() {
if (dirtyConfig) {
validateValueFrom();
validateValueTo();
validateStepSize();
validateValues();
warnAboutFloatingPointError();
dirtyConfig = false;
}
}
Expand Down

1 comment on commit ec7f7cb

@ansman
Copy link
Contributor

@ansman ansman commented on ec7f7cb Sep 2, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If a warning is printed why even allow floats?

Please sign in to comment.