I have a NumberPicker that has a formatter that formats the displayed numbers either when the NumberPicker spins or when a value is entered manually. This works fine, but when the NumberPicker is first shown and I initialize it with setValue(0)
the 0 does not get formatted (it should display as "-" instead of 0). As soon as I spin the NumberPicker from that point on everything works.
How can I force the NumberPicker to format always - Both on first rendering and also when I enter a number manually with the keyboard?
This is my formatter
public class PickerFormatter implements Formatter {
private String mSingle;
private String mMultiple;
public PickerFormatter(String single, String multiple) {
mSingle = single;
mMultiple = multiple;
}
@Override
public String format(int num) {
if (num == 0) {
return "-";
}
if (num == 1) {
return num + " " + mSingle;
}
return num + " " + mMultiple;
}
}
I add my formatter to the picker with setFormatter()
, this is all I do to the picker.
picker.setMaxValue(max);
picker.setMinValue(min);
picker.setFormatter(new PickerFormatter(single, multiple));
picker.setWrapSelectorWheel(wrap);
I had the same problem and I used the
setDisplayedValues()
method instead.This doesn't allow the user to set the value manually in the picker though.
Here's my solution based on answers by torvin and Sebastian. You don't have to subclass anything or use reflection.
dgel's solution doesn't work for me: when I tap on the picker, formatting disappears again. This bug is caused by input filter set on
EditText
insideNumberPicker
whensetDisplayValues
isn't used. So I came up with this workaround:The following solution worked out for me for APIs 18-26 without using reflection, and without using
setDisplayedValues()
.It consists of two steps:
Make sure the first element shows by setting it's visibility to invisible (I used Layout Inspector to see the difference with when it shows, it's not logical but
View.INVISIBLE
actually makes the view visible).Subclass NumberPicker and make sure no click events go through so the glitch where picker elements disapear on touch can't happen.
I managed to fix it by calling
just after setting the formatter.
Calling the private method
changeValueByOne()
via reflection as described in an earlier answer works for me onAPI Level 16
(Android 4.1.2 and up), but it does not seem to help onAPI Level 15
(Android 4.0.3), however!What works for me on API Level 15 (and up) is to use your own custom formatter to create String array and pass that with the method
setDisplayedValues()
to the number picker.See also: Android 3.x and 4.x NumberPicker Example