androidandroid-number-picker

How to customize value for numbers in NumberPicker in android?


I have a number picker for setting a data limit in MB. right now, I have numberPicker, contains numeric values in sequence like [1,2,3,....., 2000 MB].

But I want a numberPicker that should contain numeric values like [100,200,300,...., 2000MB]. How can I do this?


Solution

  • Displayed array values for your picker

    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", .....}; */
    

    Set arr in your picker :

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

    get/set the value of the picker :

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