Using SimpleAdapter with Spinner

前提是你 提交于 2019-12-07 00:13:37

问题


I am new to Android development. I am trying to populate a spinner by using the SimpleAdapter. But spinner's list is showing blank element. When I click any element, its text is shown properly in Toast. Please tell me what is the problem in my code below.

 public void onCreate(Bundle savedInstanceState) {

  private List<Map<String, String>> data = new ArrayList<Map<String, String>>();

  String[] from = new String[] { "colorsData" };
  int[] to = new int[] { R.id.spinner };

  String[] colors = getResources().getStringArray(R.array.colorsData);

  for (int i = 0; i < colors.length; i++) {
   data.add(addData(colors[i]));
  }

  Spinner spinner = (Spinner) findViewById(R.id.spinner);

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, data, android.R.layout.simple_spinner_item, from, to);
  simpleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinner.setAdapter(simpleAdapter);

  spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
    Toast.makeText(
      parent.getContext(),
      "Selected Color:-  "
        + parent.getItemAtPosition(position),
      Toast.LENGTH_LONG).show();
   }
  });
 }

 private Map<String, String> addData(String colorName) {
  Map<String, String> mapList = new HashMap<String, String>();
  mapList.put("colorsData", colorName);
  return mapList;
 }

回答1:


I'm about 95% sure that your to array should be declared as:

  int[] to = new int[] { android.R.id.text1 };

Give that a try.


EDIT (based on comments below):

It seems there was a bug in older versions of AndroidOS which caused that IllegalStateException. (I didn't see the exception in 2.2, but I did see it in 1.5 in the emulator.) The bug can be worked around by adding a ViewBinder to the SimpleAdapter. ViewBinder isn't hard to implement; here's an example:

    SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {

        public boolean setViewValue(View view, Object data,
                String textRepresentation) {
            // We configured the SimpleAdapter to create TextViews (see
            // the 'to' array), so this cast should be safe:
            TextView textView = (TextView) view;
            textView.setText(textRepresentation);
            return true;
        }
    };
    simpleAdapter.setViewBinder(viewBinder);

I blogged about this here.



来源:https://stackoverflow.com/questions/4383913/using-simpleadapter-with-spinner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!