设置NumberPicker的增加/减少间隔

Ism*_*mic 5 android

是否可以将NumberPicker的增加/减少间隔设置为其他值?例如50(50,100,150,200,250等)?或者它需要一些定制/黑客?

iTu*_*rki 6

我想你可以这样做:

  • 初始化选择器的显示数组值:

    int NUMBER_OF_VALUES = 10; //num of values in the picker
    int PICKER_RANGE = 50;
    ...
    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 = {"50", "100", "150", .....}; */
    
    Run Code Online (Sandbox Code Playgroud)
  • 将显示的数组设置为选择器:

    /* 
    NOTE: Your picker range has to be [0, displayedValues.size()-1] to be 
          consistent with the array index (displayedValues index).
    */
    //ToDo: Initialize the picker first.
    numPicker.setMinValue(0); 
    numPicker.setMaxValue(displayedValues.size()-1);
    numPicker.setDisplayedValues(displayedValues);
    
    Run Code Online (Sandbox Code Playgroud)
  • 当您想获取/设置选择器的值时:

    //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("150") )
             numPicker.setValue(i);
    
    Run Code Online (Sandbox Code Playgroud)

最后,有一个很容易定制的小部件叫做android-wheel.如果您愿意,可以查看并使用它.