android - 将 SimpleAdapter 与微调器一起使用

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

最佳答案

我大约 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 .

关于android - 将 SimpleAdapter 与微调器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383913/

相关文章:

android - 文字转语音不适用于 Android 设备

java - 按钮 onclicklistener 中的 Android 微调器

android - 如何在简单适配器的 ImageView 中显示图像?

android - 使用 SimpleAdapter 将背景图像应用于 ListView

android - 自定义 android 微调器

java - onActivityResult 之后值被设置为 null

java - Android:从 ArrayList 设置资源字符串 ID?

android - 如何使用默认的 Android 可绘制对象

android - 以编程方式切换复选框

Android:自定义微调器大小问题