Android - Advanced Usage for Spinner.OnItemSelectedListener

189 views Asked by At

I usually use boolean for this but in this situation I can not. I have a code like below on my Spinner and everything works fine :

spin.setOnItemSelectedListener(new OnItemSelectedListener() {

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

                        carNames = brand.getChildCarNames(brand.getListDataHeader().get(position));
                        makeAndShowDialogBox();

            }

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

            }

        });

The problem is when I use bolean what happens is that the choice that comes as Default is not showing the DialogBox if user chooses that Default value as-well. Such as "Tomato" comes as Default and user wants to select "Tomato" as well; nothing happens than.

What I want to do is also prevent this dialog box coming asap when Activity is opened but also I want to prevent "on selection of default value nothing happens" issue.

So, Is there any way to check exactly if the User pressed to select or not?

1

There are 1 answers

2
ztan On BEST ANSWER

You can use a Boolean variable to determine if the spinner is just loaded, so you can prevent the dialog to show when the Activity is opened (or onResume). You can declare a variable outside the listener, and change its value inside the listener. Its value is changed inside the listener, so you have to do final Boolean array instead of regular Boolean.

You can try with the following code:

  final Boolean[] spinnerLoaded = {false};

     spin.setOnItemSelectedListener(new OnItemSelectedListener() {

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

                if (!spinnerLoaded[0]) {
                    spinnerLoaded[0] = true;
                }
                else {
                   carNames = brand.getChildCarNames(brand.getListDataHeader().get(position));
                   makeAndShowDialogBox();                
                }
           }

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

           }
    });