Search code examples
androidnumberpicker

Android numberpicker negative values


I have A array that have negative and positive values, but when I start the app I only can see the minimum value in the picker.

int min = -25;
int max = 100;
int jumpBy = 5;

        String [] refl_Str = new String[((max-min)/jumpBy)+1];


        for (int i = 0; i < refl_Str.length; i++) 
        {
            refl_Str[i] = Integer.toString(min+(i*jumpBy));


        }

        np.setDisplayedValues(refl_Str);

When I add:

np.setMaxValue(100);
np.setMinValue(-25);

I get error on negative values in the numberpicker.


Solution

  • you can use following code to do that:

    final int minValue = -25
    final int maxValue = 100
    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