我是Android开发的新手。我正在尝试使用SimpleAdapter填充微调器。但是微调框的列表显示空白元素。当我单击任何元素时,其文本将正确显示在Toast中。请在下面的代码中告诉我是什么问题。

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

最佳答案

我大约有95%的把握将to数组声明为:

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

试试看。

编辑(基于以下评论):

似乎旧版本的AndroidOS中存在一个错误,该错误导致了IllegalStateException。 (我没有在2.2中看到该异常,但在模拟器中却在1.5中看到了该异常。)可以通过将ViewBinder添加到SimpleAdapter来解决该错误。 ViewBinder并不难实现;这是一个例子:
    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);

我写了关于here的博客。

关于android - 在Spinner中使用SimpleAdapter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4383913/

10-08 21:17