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

时间:2016-01-04 06:15:15

标签: android android-number-picker

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

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

3 个答案:

答案 0 :(得分:2)

选择器显示的数组值

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);

获取/设置选择器的值:

//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);

答案 1 :(得分:0)

尝试以下代码

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);

答案 2 :(得分:0)

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);