Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android spinner, nothing selected

I am having a problem when that my spinner is accessing the first case and redirecting immediately. How do I use the:

@Override
    public void onNothingSelected(AdapterView<?> view); {
        // TODO Auto-generated method stub

    }

method correctly to stay on the page before the user makes a selection. Below is my code.

// Creating adapter for spinner & choosing Drop down layout style - list view
    ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.event,android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(adapter);

    //spinner needs to know who is responsible for handling events
    spinner.setOnItemSelectedListener(this);
}

@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {

    //casting the view to textView
    TextView myText=(TextView) view;

    // use .getText to display what text was selected by user
    Toast.makeText(this,"You Selected "+myText.getText(),Toast.LENGTH_SHORT).show();



    switch (pos) {
        case (0):
            //Case selection redirecting user to 'Training Table'
            Intent a = new Intent(Calendar.this, TrainingTable.class);
            Calendar.this.startActivity(a);
            break;
        case (1):
            //Case selection redirecting user to 'Race Table'
            Intent b = new Intent(Calendar.this, Races.class);
            Calendar.this.startActivity(b);
            break;

        case (2):
            //Case selection redirecting user to 'Workshops page'
            Intent c = new Intent(Calendar.this, Workshops.class);
            Calendar.this.startActivity(c);
            break;
    }
like image 566
user3872519 Avatar asked Jul 19 '26 14:07

user3872519


1 Answers

Force the spinner to select an item:

spinner.setSelection(0);

And then set the listener:

spinner.setOnItemSelectedListener(this);

This only needs to be done once, when the spinner is created. This way you avoid getting unwanted calls to OnItemSelectedListener which is called once by default.

like image 132
Simas Avatar answered Jul 22 '26 03:07

Simas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!