Reputation: 19378
I need to get an item's position in spinner knowing it's ID. I've tried to do it with Spinner and SpinnerAdapter classes but there are no corresponding methods there.
Thanks,
Aleksander
Upvotes: 4
Views: 18884
Reputation: 6617
well if u use this u can get the position no of the item then u can match with ur array of values
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
system.out.println(arg2);
}
here arg2 is the index of the selected items position , rest i hope u can manage
Upvotes: 1
Reputation: 61
Here's how I did it last night for the first time:
Spinner mySpn = (Spinner) findViewById(R.id.my_spinner);
String spnItem = (String) mySpn.getItemAtPosition(mySpn.getSelectedItemPosition());
Upvotes: 6
Reputation: 42155
Try this:
static final int getAdapterPositionById(final Adapter adapter, final long id) throws NoSuchElementException {
final int count = adapter.getCount();
for (int pos = 0; pos < count; pos++) {
if (id == adapter.getItemId(pos)) {
return pos;
}
}
throw new NoSuchElementException();
}
It's generic enough to work for any adapter type that supports ids (e.g., implements Adapter#getItemId(int position)
in a meaningful way)
Upvotes: 6
Reputation: 5993
you can query the selected position by Spinner.getSelectedItemPosition()
or alternatively you will get the selected item position if you override the method onItemSelected()
Upvotes: 4
Reputation: 10031
You create the Spinner items via your SpinnerAdapter, so you determine the position of the items. If you create the Spiner items from some kind of collection, you could search that for the ID.
Upvotes: 2