100

Is there a way to use the Android NumberPicker widget for choosing strings instead of integers?

timoschloesser
  • 2,679
  • 4
  • 22
  • 32

5 Answers5

249
NumberPicker picker = new NumberPicker(this);
picker.setMinValue(0);
picker.setMaxValue(2);
picker.setDisplayedValues( new String[] { "Belgium", "France", "United Kingdom" } );
nan
  • 2,506
  • 1
  • 11
  • 3
  • 3
    The key for me there was you have to set the displayedValues AND the min and max before it works. Thanks. – Ben Clayton Aug 29 '13 at 08:20
  • This's much better than the chosen answer above. – Linh Lino Feb 18 '14 at 02:25
  • 2
    But when i click on the text, the soft keyboard pops out and I can edit the text. – Confuse Sep 11 '14 at 11:25
  • 15
    @ArulxZ If you haven't already figured this out, just call picker.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); to prevent the keyboard from popping up. – Karim Varela Jun 01 '15 at 20:21
  • This helped me! But it appears the value 0 and I can't remove it.. Any idea? To explain in my picker appears 0, Belgium, France, United Kingdom – user4292106 Mar 18 '16 at 11:36
  • you saved my day ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ – Leo Nguyen Mar 28 '16 at 07:26
  • **FYI**: input values from keyboard can be disabled by `picker.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCE‌​NDANTS);` as @KarimVarela mentioned, however it can be very useful. It allows to input only existing values, and then finds appropriate index – Pavel May 15 '17 at 00:48
  • I am trying various answers from few hours but nothing is showing up. I am calling the above codes under a function when clicked on a textView – MrinmoyMk Aug 05 '20 at 15:41
39
NumberPicker numberPicker = new NumberPicker(this);
String[] arrayString= new String[]{"hakuna","matata","timon","and","pumba"};
numberPicker.setMinValue(0);
numberPicker.setMaxValue(arrayString.length-1);

numberPicker.setFormatter(new NumberPicker.Formatter() {
  @Override
  public String format(int value) {
    // TODO Auto-generated method stub
    return arrayString[value];
  }
});

hope that helps!

harshitpthk
  • 3,766
  • 2
  • 21
  • 30
  • This is by far the best answer. – samatron Sep 04 '15 at 23:21
  • if it is an array, then it doesn't have size() and get() methods. size() should be replaced with .length, and get() replaced with arrayString[value] – RexSplode Mar 03 '17 at 15:06
  • If you use formatter instead of `setDisplayedValues`, the NumberPicker won't measure its width properly, so your text might be clipped even if it can fit properly. – Matvey Rybakov Sep 28 '17 at 09:39
15
String value = String.valueOf(picker.getValue());

You could mean something else, but it isn't very clear what you mean.

UPDATED:

You can fake it by setting your own formatter:

CountryFormatter implements Formatter {
    public String toString(int value) {
        switch(value) {
            case 0:
                return "England";
            case 1:
                return "France";
        }
        return "Unknown";
    }
}

picker.setFormatter(new CountryFormatter());

getValue() will still return an int, so you probably want to map the names of countries to their ids.

ADDED: The implementation of NumberPicker has:

public void setRange(int start, int end, String[] displayedValues)

Which seems to do a better job of what you want then the above formatter.. although it isn't mentioned in the documentation so probably isn't part of the public api

FunkTheMonk
  • 10,631
  • 1
  • 27
  • 37
  • I would like to use it to choose for example a country. Just like the Spinner Widget does, but without opening an additional frame at the bottom to choose a value. – timoschloesser Nov 22 '11 at 15:04
  • Updated answer, however there are probably better ways to list countries than trying to hack NumberPicker to do this sort of thing. – FunkTheMonk Nov 22 '11 at 15:58
  • @FunkTheMonk I couldn't find this `setRange()` method in the docs at all! Any ideas why? – iTurki Aug 12 '12 at 23:15
  • None documented methods aren't part of the public API - they aren't officially supported by google and they will probably change in the future - you use at your own risk. – FunkTheMonk Aug 13 '12 at 13:16
  • 1
    In my case, this solution had a small bug, when touching one of the options, it glitched or disappeared, i dont know very well why. nan's answer didnt had this issue. Anyone can tell me what could be happening? Anyway, i think nan's answer is better and should be the accepted answer. But perhaps i'm missing something? – acrespo Dec 06 '13 at 19:09
  • I had this problem: `when touching one of the options, it glitched or disappeared`. The solution was to use setDisplayedValues together with `android:descendantFocusability="blocksDescendants"`. At least it loks ok now with this settings. – marcinj Jan 20 '17 at 00:24
  • I found a solution for the glitch that works in APIs 18-26 without using reflection and without using `setDisplayedValues()` here https://stackoverflow.com/a/44949069/3918479 – Sebastian Jul 06 '17 at 12:40
8

try this solution, may help you

    NumberPicker pickers = new NumberPicker(this);
    String[] arrayPicker= new String[]{"abc","def","ghi","jkl","mno"};

    //set min value zero
    pickers.setMinValue(0);
    //set max value from length array string reduced 1
    pickers.setMaxValue(arrayPicker.length - 1);
    //implement array string to number picker
    pickers.setDisplayedValues(arrayPicker);
    //disable soft keyboard
    pickers.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
    //set wrap true or false, try it you will know the difference
    pickers.setWrapSelectorWheel(false);

    //create button to test selected text string
    btnPicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //get position (int) from number picker
            int pos = pickers.getValue();
            //get string from number picker and position
            String selecPicker = arrayPicker[pos];  
            //test toast to get selected text string
            Toast.makeText(context, selecPicker , Toast.LENGTH_SHORT).show();

        }
    });
Irvan Dwi Pangga
  • 209
  • 4
  • 13
0

This worked for me.

public class YourClassName extends AppCompatActivity {

NumberPicker picker = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity_layout_file);

    picker = (NumberPicker) findViewById(R.id.pickerId_From_your_Layout_file);

     picker.setMinValue(0);
    picker.setMaxValue(3);
    picker.setDisplayedValues(new String[]{"English", "French","Kiswahili","عربى"});
}
}
ADM
  • 16,256
  • 11
  • 37
  • 69