如何从android中的微调器中获取选定的项目?
问问题
2600 次
3 回答
1
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
笔记:
Spinner 小部件的文档清楚地指出:
A spinner does not support item click events. Calling this
method will raise an exception.
如上所述,最好改用OnItemSelectedListener()。
于 2010-08-02T12:55:27.510 回答
0
在您的活动中:
mSpinner = (Spinner) findViewById(R.id.my_spinner);
// Define your adapter, in my case I have a class (SpinnerData) so I get an ID instead of the spinner's text
ArrayAdapter<SpinnerData> myadapter = new ArrayAdapter<SpinnerData>(
this, android.R.layout.simple_spinner_item, new SpinnerData [] {
new SpinnerData("1","Item 1"),
new SpinnerData("2","Item 2")
});
myadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(myadapter);
mSpinner.setOnItemSelectedListener(this);
如果表单中有其他触发 onItemSelected 事件的元素,这将很有用:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id{
SpinnerData sd;
switch (parent.getId()) {
case R.id.my_spinner:
sd = (SpinnerData)mSpinner.getSelectedItem();
// do something with sd.id
break;
... }
作为参考, SpinnerData 类:
public class SpinnerData {
public String id;
public String name;
public SpinnerData(String _id, String _name) {
this.id = _id;
this.name = _name;
}
public String toString() {
return this.name;
}
}
希望能帮助到你。
于 2011-03-04T12:12:02.763 回答
0
试试这个代码..
sp2.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long id) {
// TODO Auto-generated method stub
int selected_item_position = arg2;
String selected_item=sp2.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
于 2012-08-02T03:50:24.247 回答