[android] How do I create an Android Spinner as a popup?

I want to bring up a spinner dialog when the user taps a menu item to allow the user to select an item.

Do I need a separate dialog for this or can I use Spinner directly? I see this link, mentions a MODE_DIALOG option but it doesn't seem to be defined anymore. AlertDialog may be OK but all the options say "clicking on an item in the list will not dismiss the dialog" which is what I want. Any suggestion?

Ideally, the code would be similar to the case where the spinner is shown on the screen:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
     android.R.layout.simple_spinner_item, items);              
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(adapter);  
// myspinner.showAsDialog() <-- what i want             

This question is related to android dialog spinner

The answer is


If you want to show it as a full screen popup, then you don't even need an xml layout. Here's how do do it in Kotlin.

 val inputArray: Array<String> = arrayOf("Item 1","Item 2")
                val alt_bld =  AlertDialog.Builder(context);
                alt_bld.setTitle("Items:")
                alt_bld.setSingleChoiceItems(inputArray, -1) { dialog, which ->
                    if(which == 0){
                        //Item 1 Selected
                    }
                    else if(which == 1){
                        //Item 2 Selected
                    }
                    dialog.dismiss();

                }

                val alert11 = alt_bld.create()
                alert11.show()

android:spinnerMode="dialog"

// Creating adapter for spinner

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, categories);

// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

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

This is from the Android SDK source code. As you can see you have a special constructor to create a Spinner with the specified mode you wanna use.

Hope it will help you :)

 /**
     * Construct a new spinner with the given context's theme, the supplied attribute set,
     * and default style. <code>mode</code> may be one of {@link #MODE_DIALOG} or
     * {@link #MODE_DROPDOWN} and determines how the user will select choices from the spinner.
     *
     * @param context The Context the view is running in, through which it can
     *        access the current theme, resources, etc.
     * @param attrs The attributes of the XML tag that is inflating the view.
     * @param defStyle The default style to apply to this view. If 0, no style
     *        will be applied (beyond what is included in the theme). This may
     *        either be an attribute resource, whose value will be retrieved
     *        from the current theme, or an explicit style resource.
     * @param mode Constant describing how the user will select choices from the spinner.
     * 
     * @see #MODE_DIALOG
     * @see #MODE_DROPDOWN
     */
    public Spinner(Context context, AttributeSet attrs, int defStyle, int mode) {
        super(context, attrs, defStyle);

Here is an Spinner subclass which overrides performClick() to show a dialog instead of a dropdown. No XML required. Give it a try, let me know if it works for you.

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;
    }
}

For more information read this article: How To Make Android Spinner Options Popup In A Dialog


Here is a Kotlin version based on the accepted answer.

I'm using this dialog from an adapter, every time a button is clicked.

yourButton.setOnClickListener {
    showDialog(it /*here I pass additional arguments*/)
}

In order to prevent double clicks I immediately disable the button, and re-enable after the action is executed / cancelled.

private fun showDialog(view: View /*additional parameters*/) {
    view.isEnabled = false

    val builder = AlertDialog.Builder(context)
    builder.setTitle(R.string.your_dialog_title)

    val options = arrayOf("Option A", "Option B")

    builder.setItems(options) { dialog, which ->
        dialog.dismiss()

        when (which) {
            /* execute here your actions */
            0 -> context.toast("Selected option A")
            1 -> context.toast("Selected option B")
        }

        view.isEnabled = true
    }

    builder.setOnCancelListener {
        view.isEnabled = true
    }

    builder.show()
}

You can use this instead of a context variable if you are using it from an Activity.


You can use a spinner and set the spinnerMode to dialog, and set the layout_width and layout_height to 0, so that the main view does not show, only the dialog (dropdown view). Call performClick in the button click listener.

    mButtonAdd.setOnClickListener(view -> {
        spinnerAddToList.performClick();
    });

Layout:

    <Spinner
        android:id="@+id/spinnerAddToList"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="10dp"
        android:prompt="@string/select_from_list"
        android:theme="@style/ThemeOverlay.AppCompat.Light"
        android:spinnerMode="dialog"/>

The advantage of this is you can customize your spinner any way you want.

See my answer here to customize spinner: Overriding dropdown list style for Spinner in Dialog mode


MODE_DIALOG and MODE_DROPDOWN are defined in API 11 (Honeycomb). MODE_DIALOG describes the usual behaviour in previous platform versions.


In xml there is option

android:spinnerMode="dialog"

use this for Dialog mode


You can create your own custom Dialog. It's fairly easy. If you want to dismiss it with a selection in the spinner, then add an OnItemClickListener and add

int n = mSpinner.getSelectedItemPosition();
mReadyListener.ready(n);
SpinnerDialog.this.dismiss();

as in the OnClickListener for the OK button. There's one caveat, though, and it's that the onclick listener does not fire if you reselect the default option. You need the OK button also.

Start with the layout:

res/layout/spinner_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content">
<TextView 
    android:id="@+id/dialog_label" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
    android:hint="Please select an option" 
    />
<Spinner
    android:id="@+id/dialog_spinner" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
    />
<Button
    android:id="@+id/dialogOK" 
    android:layout_width="120dp"
    android:layout_height="wrap_content" 
    android:text="OK"
    android:layout_below="@id/dialog_spinner"
    />
<Button
    android:id="@+id/dialogCancel" 
    android:layout_width="120dp"
    android:layout_height="wrap_content" 
    android:text="Cancel"
    android:layout_below="@id/dialog_spinner"
    android:layout_toRightOf="@id/dialogOK"
    />
</RelativeLayout>

Then, create the class:

src/your/package/SpinnerDialog.java:

public class SpinnerDialog extends Dialog {
    private ArrayList<String> mList;
    private Context mContext;
    private Spinner mSpinner;

   public interface DialogListener {
        public void ready(int n);
        public void cancelled();
    }

    private DialogListener mReadyListener;

    public SpinnerDialog(Context context, ArrayList<String> list, DialogListener readyListener) {
        super(context);
        mReadyListener = readyListener;
        mContext = context;
        mList = new ArrayList<String>();
        mList = list;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.spinner_dialog);
        mSpinner = (Spinner) findViewById (R.id.dialog_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String> (mContext, android.R.layout.simple_spinner_dropdown_item, mList);
        mSpinner.setAdapter(adapter);

        Button buttonOK = (Button) findViewById(R.id.dialogOK);
        Button buttonCancel = (Button) findViewById(R.id.dialogCancel);
        buttonOK.setOnClickListener(new android.view.View.OnClickListener(){
            public void onClick(View v) {
                int n = mSpinner.getSelectedItemPosition();
                mReadyListener.ready(n);
                SpinnerDialog.this.dismiss();
            }
        });
        buttonCancel.setOnClickListener(new android.view.View.OnClickListener(){
            public void onClick(View v) {
                mReadyListener.cancelled();
                SpinnerDialog.this.dismiss();
            }
        });
    }
}

Finally, use it as:

mSpinnerDialog = new SpinnerDialog(this, mTimers, new SpinnerDialog.DialogListener() {
  public void cancelled() {
    // do your code here
  }
  public void ready(int n) {
    // do your code here
  }
});

Try this:

Spinner popupSpinner = new Spinner(context, Spinner.MODE_DIALOG);

See this link for more details.


Adding a small attribute as android:spinnerMode="dialog" would show the spinner contents in a pop-up.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to dialog

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) How to change DatePicker dialog color for Android 5.0 Android simple alert dialog Swift alert view with OK and Cancel: which button tapped? How to make a edittext box in a dialog How to check if activity is in foreground or in visible background? jquery ui Dialog: cannot call methods on dialog prior to initialization JavaScript: Create and save file Prevent Android activity dialog from closing on outside touch How to use OpenFileDialog to select a folder?

Examples related to spinner

How to add a Hint in spinner in XML Hide Spinner in Input Number - Firefox 29 How can I use onItemSelected in Android? Show default value in Spinner in android Set selected item of spinner programmatically How to set Spinner Default by its Value instead of Position? How to change spinner text size and text color? WPF loading spinner How do I create an Android Spinner as a popup? How to add items to a spinner in Android?