Spinnerを使用したSimpleadapterを使用します
-
10-10-2019 - |
質問
私はAndroid Developmentを初めて使用しています。 Simpleadapterを使用してスピナーを入力しようとしています。しかし、Spinnerのリストには空白の要素が表示されています。要素をクリックすると、そのテキストはトーストに適切に表示されます。以下の私のコードの問題は何ですか。
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の古いバージョンにはバグがあったようで、その違法な標識を引き起こしました。 (2.2で例外は見られませんでしたが、エミュレータで1.5でそれを見ました。)Biewbinderを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);
私はこれについてブログに書きました ここ.
所属していません StackOverflow