问题
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
int minValue = 5;
int maxValue = 60;
int step = 5;
String[] numberValues = new String[maxValue/minValue];
for (int i = minValue; i <= maxValue; i+= step)
{
numberValues[(i/step)-1] = String.valueOf(i);
}
mNumberPicker = (NumberPicker)findViewById(R.id.numberPicker);
mNumberPicker.setMinValue(0);
mNumberPicker.setMaxValue(60);
//mNumberPicker.setValue(20);
mNumberPicker.setWrapSelectorWheel(false);
mNumberPicker.setDisplayedValues(numberValues);
There is also an error message in the logcat
java.lang.ArrayIndexOutOfBoundsException: length=12; index=12
I don't understand why as the number has been created successfully so why does the number picker crash when it's chosen?
回答1:
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);
}
回答2:
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 = new String[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);
`
来源:https://stackoverflow.com/questions/31036586/android-number-picker-using-steps