将SimpleAdapter与Spinner一起使用

时间:2010-12-08 03:31:33

标签: android spinner simpleadapter

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

1 个答案:

答案 0 :(得分:5)

我大约95%确定你的to数组应该声明为:

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

试一试。


编辑(根据以下评论):

似乎旧版AndroidOS中存在导致IllegalStateException的错误。 (我没有在2.2中看到异常,但我确实在模拟器中看到了1.5。)可以通过向SimpleAdapter添加ViewBinder来解决这个问题。 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