I've thought of some less than elegant ways to solve this, but I know I must be missing something.
My onItemSelected
fires off immediately without any interaction with the user, and this is undesired behavior. I wish for the UI to wait until the user selects something before it does anything.
I even tried setting up the listener in the onResume()
, hoping that would help, but it doesn't.
How can I stop this from firing off before the user can touch the control?
public class CMSHome extends Activity {
private Spinner spinner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Heres my spinner ///////////////////////////////////////////
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.pm_list, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
};
public void onResume() {
super.onResume();
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Intent i = new Intent(CMSHome.this, ListProjects.class);
i.putExtra("bEmpID", parent.getItemAtPosition(pos).toString());
startActivity(i);
Toast.makeText(parent.getContext(), "The pm is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
}
No unwanted events from the layout phase if you defer adding the listener till the layout is finished:
I got a very simple answer , 100% sure it works:
Referring to the answer of Dan Dyer, try to register the
OnSelectListener
in apost(Runnable)
method:By doing that for me the wished behavior finally occurred.
In this case it also means that the listener only fires on a changed item.
This will happen if you are making selection in code as;
Instead of above statement use
Edit: This method doesn't work for Mi Android Version Mi UI.
My solution uses
onTouchListener
but doesn't restricts from its use. It creates a wrapper foronTouchListener
if necessary where setuponItemSelectedListener
.I was in similar situation, and I have a simple solution working for me.
It seems like methods
setSelection(int position)
andsetSelected(int position, boolean animate)
have different internal implementation.When you use the second method
setSelected(int position, boolean animate)
with false animate flag, you get the selection without firingonItemSelected
listener.