Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an item's position from item's ID in android spinner?

Tags:

android

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

like image 819
Alexander Oleynikov Avatar asked Dec 02 '22 05:12

Alexander Oleynikov


2 Answers

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)

like image 198
Joe Avatar answered Dec 05 '22 10:12

Joe


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());
like image 20
Vaughan Wynne-Jones Avatar answered Dec 05 '22 09:12

Vaughan Wynne-Jones