本文是我从网上搜集然后自己整理到自己项目中的~~
Spinner 控件在使用ArrayAdapter的时候难免有时不想放入Array数组,前几天我这边往spinner控件中放入了list,可放入适配器的时候老是报错,解决方案如下:从方法里摘抄的,无方法名 谅解~
//方法的变量声明
private String[] reason;
Hashtable hnameids;
//list中获取的是id-name的数据
List list = parseResult(result); //这里的ParseResult方法是对从数据库查询出的数据进行规整
hnameids=new Hashtable();
reason = new String[list.size()];
for (int i = 0; i
//这里是把list中的id-name读取出来存入hashtable中了
hnameids.put(list.get(i).getCategoryName(),list.get(i).getCategoryID());
}
ArrayAdapter adapter = new ArrayAdapter(EmployeeLeave.this,android.R.layout.select_dialog_item , list);
spinnerReason.setAdapter(adapter);
下面有需求啦~点击spinner中显示的某一项的时候需要把某项对应的id拿到。
//这些都是全局变量,方便理解我拿上来了~
private Spinner spinnerReason;
private int categoryID;
spinnerReason=(Spinner)findViewById(R.id.spinnerReason);
spinnerReason.setOnItemSelectedListener(new OnItemSelectedListener() {
//当选中某一项的时候,然后hashtable就派上用场了,根据选中的名字,把id赋给全局变量categoryID
@Override
public void onItemSelected(AdapterView> parent, View view,
int position, long id) {
String date = parent.getItemAtPosition(position).toString();
categoryID = hnameids.get(date);
}
@Override
public void onNothingSelected(AdapterView> arg0) {
}
});
好了,需求达到了,选中某一项然后可得到选中当前项的ID~~
整理不易,也请大家多提提意见