android 如何在 NumberPicker 中自定义数字的值?

How to customize value for numbers in NumberPicker in android?

我有一个数字选择器,用于设置以 MB 为单位的数据限制。现在,我有 numberPicker,包含按顺序排列的数值,如 [1,2,3,....., 2000 MB]。

但是我想要一个 numberPicker,它应该包含像 [100,200,300,...., 2000MB] 这样的数值。 我该怎么做?

为您的选择器显示数组值

int NUMBER_OF_VALUES = 20; //num of values in the picker
int PICKER_RANGE = 100;
...
String[] displayedValues  = new String[NUMBER_OF_VALUES];
//Populate the array
for(int i=0; i<NUMBER_OF_VALUES; i++)
    displayedValues[i] = String.valueOf(PICKER_RANGE * (i+1));
/* OR: if the array is easy to be hard-coded, then just hard-code it:
   String[] displayedValues = {"100", "200", "300", .....}; */

在您的选择器中设置 arr :

numPicker.setMinValue(0); 
numPicker.setMaxValue(displayedValues.size()-1);
numPicker.setDisplayedValues(displayedValues);

get/set选择器的值:

//To get the current value in the picker
choosenValue = displayedValues[numPicker.getValue()]; 
//To set a new value (let's say 150)
for( int i=0; i<displayedValues.length ; i++ )
    if( displayedValues[i].equals("300") )
         numPicker.setValue(i);

试试下面的代码

int start = 100;
        String[] numbers = new String[20];
        for(int i =0 ; i < 20 ; i++) {
            numbers[i] = start + "";
            start = start + 100;
        }
        NumberPicker numberPicker = (NumberPicker) findViewById(R.id.id_number_picker);
        numberPicker.setMaxValue(20);
        numberPicker.setMinValue(1);
        numberPicker.setDisplayedValues(numbers);
final String[] nums = new String[21];
        for(int i=0; i<nums.length; i++) {
            nums[i] = Integer.toString((i+1)*100);
        }

numberPicker.setMinValue(0);
numberPicker.setMinValue(19);
numberPicker.setDisplayedValues(nums);