How To Make Android Spinner Options Popup in a Dialog

By , 28 May 2014

How To Make Android Spinner Options Popup in a Dialog

The earlier versions of Android always showed spinner options in a dialog. Then I think devices got bigger and the powers that be decided to use a dropdown list for spinner options instead of a dialog. It's a sensible choice because the dropdowns look and operate better than the dialog - sometimes.

It's the sometimes that is the problem. For lists with a lot of data it makes better sense to use a full screen dialog than a small dropdown. The screenshots below show how much better the usability of a dialog selection is for our app, The Game Of Your Life.

How To Make Android Spinner Options Popup in a Dialog

Unfortunately the Android API doesn't give us an option to select between the two behaviours, but there is a way to force the spinner to use a dialog by extending the default Spinner class. Here is the code.

    public class DialogSpinner extends Spinner {
        public DialogSpinner(Context context) {
            super(context);
        }

        @Override 
        public boolean performClick() {
            new AlertDialog.Builder(getContext()).setAdapter((ListAdapter) getAdapter(), 
                new DialogInterface.OnClickListener() {
                    @Override public void onClick(DialogInterface dialog, int which) {
                        setSelection(which);
                        dialog.dismiss();
                    }
                }).create().show();
            return true;
        }
    }

If you like, you could further enhance this class to conditionally use a dialog or dropdown based on whatever logic you need. Note, you'll have to be sure to use a ListAdapter with this class or you'll get a ClassCastException.

It took a while and a fair bit of digging through the source code to figure this problem out so I hope you find it useful. If you're interesting in downloading the motivation app in the screenshot, it's available for free from Google Play.

Happy coding.

About Roger Keays

How To Make Android Spinner Options Popup in a Dialog

Leave a Comment

Please visit https://rogerkeays.com/how-to-make-android-spinner-options-popup-in-a-dialog to add your comments.

Comment posted by: Umesh, last year

i had to use these constructors... otherwise it is giving error

public NoTitleSpinner(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public NoTitleSpinner(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public NoTitleSpinner(Context context) {
    super(context);
}

 

thanks for the solution. worked for me.

Comment posted by: marc, 2 years ago

HI, this is what Im trying to do, something like an optgroup in html, but I cant find how to do this. Would you mind to share with me a bit more of code so I can look how you did this?

 

thanks