3

Number picker

np = (NumberPicker) findViewById(R.id.numberPicker1);
    np.setMaxValue(200);
    np.setMinValue(1);
    Button b = (Button) findViewById(R.id.button1);

when I scroll numbers should go 1 2 3 ... etc ..

what I want is when scrolling its should go 5 10 15 etc

how to do it ?

3 Answers3

5

This code snippet should fix your problem;

NumberPicker np = (NumberPicker) findViewById(R.id.numberPicker1);
String[] numbers = new String[200/5];
for (int i=0; i<numbers.length; i++)
    numbers[i] = Integer.toString(i*5+5);
np.setDisplayedValues(numbers);
np.setMaxValue(numbers.length-1);
np.setMinValue(0);
np.setWrapSelectorWheel(false);

np.setOnValueChangedListener(new OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        int newValue = newVal * 5 + 5;
    }
});
Sameer Khan
  • 637
  • 6
  • 15
  • this codes works correctly but the output is give out some other values I don’t know why , but the number picker scrolling works fine. and one more thing what should I do to stay the number picker value has it is when closing .when coming back to activity after shutting down it should be the last selected value .. – Ashraf Thaikkat Apr 16 '14 at 14:28
  • Can you please elaborate? What sort of other nos. and how did you get them? I have tested this code to some extent. Your inputs would help me fix it. – Sameer Khan Apr 16 '14 at 14:31
  • 5 shows number picker output is 1 ,10 shows number picker output is 2 etc – Ashraf Thaikkat Apr 16 '14 at 14:41
  • I'll fix it and send across to you. Its simple... It is providing the index of the displayvalues index. Need to multiply by 5 and use it. – Sameer Khan Apr 16 '14 at 14:46
  • Fixed it... please use the newValue! – Sameer Khan Apr 16 '14 at 16:11
  • I select 20 from number picker and closes app and when I come back I want that 20 in number picker , can you guide me how to do it . – Ashraf Thaikkat Apr 18 '14 at 18:29
  • Please call np.setValue((value - 5)/5) when you come back. Here 'value' would be 5, 10, 15, 20, ..... – Sameer Khan Apr 18 '14 at 18:59
3

Try this :

numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

 @Override
 public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
     picker.setValue((newVal < oldVal)?oldVal-5:oldVal+5);
 }

});

Also NumberPicker in Android has a method called setDisplayedValues.

String[] minuteValues = new String[12];

for (int i = 0; i < minuteValues.length; i++) {
    String number = Integer.toString(i*5);
    minuteValues[i] = number.length() < 2 ? "0" + number : number;
}

numberPicker.setDisplayedValues(minuteValues);
vjdhama
  • 4,878
  • 5
  • 33
  • 47
1

You can use NumberPicker.Formatter to format display values. See my answer here

Community
  • 1
  • 1
easycheese
  • 5,859
  • 10
  • 53
  • 87
  • Everything fine expect that numberPicker.setValue() does not work properly in this approach. – 9re Nov 24 '15 at 06:25