我是 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 };
尝试一下。
EDIT(基于以下评论):
旧版本的 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 http://www.outofwhatbox.com/blog/2010/12/android-spinners-simpleadapter-and-maybe-viewbinder/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)