Does anyone know of an easy way to allow negative numbers with Android's default numberpicker? I understand that it's the InputFilter that disallows this, but is there any easy way to override without rewriting the whole widget?
A more generic and elegant solution is to use NumberPicker.Formatter and use only positive numbers in the NumberPicker.
Example if I want to select a number in [-50, 50]:
final int minValue = -50
final int maxValue = 50
NumberPicker numberPicker = new NumberPicker(myActivity);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(maxValue - minValue);
numberPicker.setValue(myCurrentValue - minValue);
numberPicker.setFormatter(new NumberPicker.Formatter() {
@Override
public String format(int index) {
return Integer.toString(index + minValue);
}
});
then to get back the selected value:
int myNewValue = numberPicker.getValue() + minValue
Use:
String[] nums {"-1","-2","-3","-4"};
numberpicker.setDisplayedValues(nums);
or
String[] nums = new String[4];
for(int i=0; i<nums.length; i++)
nums[i] = "-" + Integer.toString(i);
numberpicker.setDisplayedValues(nums);
Either of those will let you use any set of Strings for your NumberPicker. What you are doing is you are specifying a set of strings which you the pass to the NumberPicker. Then it will display your values instead of the default ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With