Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why onNothingSelected is not called

Spinner item getting select on Activity start up

  spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                  Toast.makeText(parent.getContext(), "The country is " +
                     position , Toast.LENGTH_LONG).show();

            }
            public void onNothingSelected(AdapterView<?> parent) {
                return;

            }
        });

when activity start onItemSelected method getting called

I want when activity start there should be no toast message .Message should be displayed when user will select an item.

like image 812
Sunny Avatar asked Nov 30 '11 04:11

Sunny


1 Answers

You have to use flag for maintaining that state. As your Activity starts the Spinner already has its first items as selected therefore its onItemSelected gets called on start up of the Activity.

You can manage it by this, take two int variables.

int first_spinner = 0, first_spinner_counter = 0;

Now when you initialize the spinner set first_spinner = 1; then add the Listener

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                  if (first_spinner_counter < first_spinner) {
                          first_spinner_counter++;
                    } 
                  else 
                  {
                     Toast.makeText(parent.getContext(), "The country is " +
                     position , Toast.LENGTH_LONG).show();
                  }
            }
            public void onNothingSelected(AdapterView<?> parent) {
                return;
            }
        });
like image 131
Lalit Poptani Avatar answered Oct 27 '22 00:10

Lalit Poptani