使用NumberPicker Widget和string

有没有办法使用Android的NumberPicker小部件selectstring,而不是整数?

NumberPicker picker = new NumberPicker(this); picker.setMinValue(0); picker.setMaxValue(2); picker.setDisplayedValues( new String[] { "Belgium", "France", "United Kingdom" } ); 
 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]; } }); 

希望有所帮助!

 String value = String.valueOf(picker.getValue()); 

你可能还有其他的意思,但是你的意思不是很清楚。

更新:

您可以通过设置自己的格式化程序来伪造它:

 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()仍然会返回一个int,所以你可能想要把国家的名字映射到他们的id。

ADDED:NumberPicker的实现有:

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

这似乎做得更好,你想要什么然后上面的格式化..虽然它没有在文档中提到,所以可能不是公共API的一部分

试试这个解决scheme,可能会帮助你

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