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 DialogUnfortunately 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.
Roger Keays is an artist, an engineer, and a student of life. He has no fixed address and has left footprints on 40-something different countries around the world. Roger is addicted to surfing. His other interests are music, psychology, languages, the proper use of semicolons, and finding good food. |