Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the step size of a NumberPicker

Is it possible to do that in a more convenient way than handling it in the OnScrollListener event? Pity it doesn't have a step size attribute...

like image 577
user940016 Avatar asked Oct 19 '12 17:10

user940016


2 Answers

The NumberPicker in Android has a method called setDisplayedValues. You can use this one to show custom values (it takes an array of Strings) and then map them when you need the value.

For example, you can create a function like this:

public String[] getArrayWithSteps (int iMinValue, int iMaxValue, int iStep)
{ 
   int iStepsArray = (iMaxValue-iMinValue) / iStep+1; //get the lenght array that will return

   String[] arrayValues= new String[iStepsArray]; //Create array with length of iStepsArray 

   for(int i = 0; i < iStepsArray; i++)
   {
     arrayValues[i] = String.valueOf(iMinValue + (i * iStep));
   }

   return arrayValues;
}

So, you should call the method> NumberPicker.setDisplayedValues, for example:

int min = 5;
int max = 180;
int step = 10;

String[] myValues = getArrayWithSteps(min, max, step); //get the values with steps... Normally 

//Setting the NumberPick (myNumberPick)
myNumberPick.setMinValue(0);
myNumberPick.setMaxValue((max-step) / min + 1); //Like iStepsArray in the function
//Because the Min and Max Value should be the range that will show. 
//For example, Min = 0 and Max = 2, so the NumberPick will display the first three strings in the array String (myValues); 
myNumberPick.setDisplayedValues(myValues);//put on NumberPicker 

For get the Value in the NumberPick:

String sValue = String.valueOf(10+(myNumberPick.getValue()*5)); //->> (iMinValue + (myNumberPick.getValue()*iStep))
like image 95
Guihgo Avatar answered Sep 22 '22 19:09

Guihgo


The NumberPicker in Android has a method called setDisplayedValues. You can use this one to show custom values (it takes an array of Strings) and then map them when you need the value. So if you need steps of 5 in an minute picker, for example, you can create an array like this:

String[] minuteValues = new String[12];

for (int i = 0; i < minuteValues.length; i++) {
    String number = Integer.toString(i*5);
    minuteValues[i] = number.length() < 2 ? "0" + number : number;
}

minutePicker.setDisplayedValues(minuteValues);

And then when you get the value in the OnValueChangeListener, you just need to cast it back to an integer:

Integer.parseInt(minuteValues[newVal]);
like image 34
kevinpelgrims Avatar answered Sep 24 '22 19:09

kevinpelgrims