Avoiding onItemSelected calls during initialization

4229 views
Skip to first unread message

Dave Orme

unread,
Nov 21, 2008, 11:39:01 PM11/21/08
to Android Developers
I have code like:

void init() {
spinner.setOnItemSelectedListener(null);
spinner.setAdapter(prioritiesAdapter);
spinner.setSelection(task.getPriority() - 1);
spinner.setOnItemSelectedListener(this);
}

@Override
public void onItemSelected(AdapterView<?> parent, View v, int
position, long id) {
Log.d(TAG, "itemSelected: " + position);
}


I would expect that I would *not* see debug messages during
initialization, because I explicitly remove the listener before I call
setSelection() and put it back after I'm done.

However, I *do* see the debug messages anyway. It's as if the
selection setting is getting queued up and running later.

So how do I make sure that my event handlers don't run during (re)
initialization?


Thanks in advance,

Dave Orme

Romain Guy

unread,
Nov 22, 2008, 3:14:57 AM11/22/08
to android-d...@googlegroups.com
> void init() {
> spinner.setOnItemSelectedListener(null);
> spinner.setAdapter(prioritiesAdapter);
> spinner.setSelection(task.getPriority() - 1);
> spinner.setOnItemSelectedListener(this);
> }

setAdapter() is not a blocking call. The items and the selection are
set in the spinner on the first layout, which happens *after* your
call to pinner.setOnItemSelectedListener(this).

> So how do I make sure that my event handlers don't run during (re)
> initialization?

Your event handler doesn't run during initialization. It runs on the
first layout.

--
Romain Guy
www.curious-creature.org

daekpony

unread,
Jan 6, 2009, 9:41:11 PM1/6/09
to Android Developers
I understand that the onItemSelected callback is run on the first
layout, but it doesn't quite make sense to me why. I'd like the
spinner to act as a simple drop down selection list that allows the
user to select a single item. The only selection completed hook I
found is the onItemSelected callback. However, if that gets called on
the spinner's layout, then I would have to differentiate in my
callback handler between onItemSelected calls due to layouts and
onItemSelected calls due to user actions. And I can't see of any way
to actually differentiate between the two. Probably I'm just unclear
on the usage pattern. But how would I go about implementing a simple
drop down selector (just like an HTML one) that will record the option
that the user selects?

thanks.

IronBlossom

unread,
May 24, 2012, 12:49:26 PM5/24/12
to android-d...@googlegroups.com
>>Your event handler doesn't run during initialization. It runs on the
first layout
 

New to android. Facing the same problem on spinner, but what do you mean by "first layout"? Is there any relationship with XML layout or you mean the first spinner.setOnItemSelectedListener(null)? 




Reply all
Reply to author
Forward
0 new messages