tags:

views:

55

answers:

1

My Activity implements OnItemSelected listener for a spinner. It has the interesting problem of firing off the onItemSelected callback when the activity shows. So I used a flag hack to solve it (I hate it, but at this point I just want the app to work).

Strangely enough, even though the callback gets called right at activity start, my actual touch selections don't work. I can touch the list, open it, see the strings from the array adapter, and even touch it to make it dismiss - but the callback is never called.

My code:

public class MyActivity extends Activity implements OnItemSelectedListener {
…
private ArrayList<String> mMyTypes = null;
private ArrayAdapter<String> mMyAdapter = null;
private Spinner mMyTypeSpinner = null;
// hack for spinner
boolean isFirstRunWithSpinner = true;

In onCreate():

mMyTypeSpinner = (Spinner) findViewById(R.id.my_activity_spinner);

mMyTypes = new ArrayList<String>();
mMyTypes.add("Test string");

mMyAdapter = new ArrayAdapter<String>(this, R.layout.custom_spinner_style, mMyTypes);
mMyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mMyTypeSpinner.setAdapter(mMyAdapter);

// spinner listener
mMyTypeSpinner.setOnItemSelectedListener(this);

The callback:

@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
 Toast
 .makeText(ConfirmEditActivity.this, "Selected", Toast.LENGTH_LONG)
 .show();
if( isFirstRunWithSpinner ) { isFirstRunWithSpinner = false; return; }
…
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
 Toast
 .makeText(ConfirmEditActivity.this, "Nothing", Toast.LENGTH_LONG)
 .show();
}

The toast is shown right when the activity is shown, but when I select items in the spinner, the spinner dismisses and no toast is displayed again (not to mention the rest of the code in the callback fails to execute).

Any observations?

I really hope this something simple...

A: 

Have you tried setOnItemClickListener() instead of setOnItemSelectedListener()?

Chris L.
java.lang.RuntimeException setOnItemClickListener cannot be used with a spinner. Thanks anyway
just_another_coder
Hmm... that's weird cause it's in the Android Documentation: http://developer.android.com/reference/android/widget/Spinner.html
Chris L.
Wow, very weird...I'll continue to play with it and see what I can come up with.
just_another_coder
A spinner does not support item click events. Calling this method will raise an exception.
just_another_coder
From: public void setOnItemClickListener (AdapterView.OnItemClickListener l)
just_another_coder