Spinner initialized when my activity starts - Android
I have Spinner which name: turListe. It gets input values from database. When i start my activity, onOtemSelected starts automatically. How can i solve this problem?
turListe.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) 开发者_C百科{
String turAdi;
Intent intent = new Intent(MainScreen.this, TarifListe.class);
Bundle bundle = new Bundle();
turAdi = arg0.getItemAtPosition(arg2).toString();
bundle.putString("turad", turAdi);
intent.putExtras(bundle);
startActivity(intent);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I solved my problem using a button next to the related spinner. I know it isn't a perfect solution, but it solved my problem in a short time.
I guess I solved it with a boolen flag as static in global declaration.
MyOnItemSelectedListener onItemSelectedListener = new MyOnItemSelectedListener(false);
sp_choose1.setOnItemSelectedListener(onItemSelectedListener);
sp_choose2.setOnItemSelectedListener(onItemSelectedListener);
onItemSelectedListener.getDataforList();
Use this class and toggle the boolean to enable or disable the onItemSelectedListener calls.
private class MyOnItemSelectedListener implements OnItemSelectedListener {
public MyOnItemSelectedListener(boolean bool){
spinner_bug = bool;
}
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext(), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
if(spinner_bug)
getDataforList();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
private void getDataforList(){
//dosomething
}
}
This is a known problem. I believe one possible workaround is the set the adapter on the spinner before you call setOnItemSelectedListener()
.
If this isn't possible then you could have a Boolean such as isAdapterSet
and have your onItemSelected()
method check it to see if it should ignore the selection event or not.
Use only OnItemSelectedListener() instead of AdapterView.OnItemSelectedListener()
精彩评论