Android Number Picker Using Steps
I have managed to create a number picker that loops through 5 to 60 in increments of 5. My only problem is that when I get to 60, the application crashes. //Number pickers
Solution 1:
I will replace question's parameter mNumberPicker to np
setDisplayedValues() : The length of the displayed values array must be equal to the range of selectable numbers which is equal to np.getMaxValue() - np.getMinValue() + 1.
So, you have to make numberValues.length() == np.getMaxValue() - np.getMinValue() + 1 true. In your case, make np.setMaxValue(12), not (60) and do like below. It will works.
Briefly, if you want 10~200 arrange in NumberPicker and expected step is 10 :
set minValue = 1, maxValue = 20 and step = 10;
int minValue = 1;
int maxValue = 12;
int step = 5;
String[] numberValues = newString[maxValue - minValue + 1];
for (int i = 0; i <= maxValue - minValue; i++) {
numberValues[i] = String.valueOf((minValue + i) * step);
}
np = (NumberPicker)findViewById(R.id.numberPicker);
np.setMinValue(minValue);
np.setMaxValue(maxValue);
np.setWrapSelectorWheel(false);
np.setDisplayedValues(numberValues);
`
Solution 2:
Change this:
for (int i = minValue; i <= maxValue; i+= step)
{
numberValues[(i/step)-1] = String.valueOf(i);
}
To this:
for (int i = 0; i < numberValues.length; i++)
{
numberValues[i] = String.valueOf(step + i*step);
}
Or if you want to keep it confusing (haven't tested but should work):
for (int i = minValue; i < maxValue; i+= step)
{
numberValues[(i/step)-1] = String.valueOf(i);
}
Solution 3:
There's another way to tackle the issue that, arguably, may seem more intuitive. It uses the onValueChange method:
@OverridepublicvoidonValueChange(NumberPicker np, int oldVal, int newVal) {
if (newVal > oldVal) {
if (newVal < np.getMaxValue())
np.setValue(newVal+(myStep-1));
}
else
np.setValue(newVal-(myStep-1));
}
Post a Comment for "Android Number Picker Using Steps"