Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a negative NumberPicker

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?

like image 211
Josh Avatar asked Jan 16 '13 11:01

Josh


2 Answers

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
like image 104
alberthier Avatar answered Oct 13 '22 17:10

alberthier


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.

like image 36
user1762507 Avatar answered Oct 13 '22 19:10

user1762507