How do I create an Android Spinner as a popup?

后端 未结 12 1755
梦如初夏
梦如初夏 2020-12-02 09:20

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 dir

相关标签:
12条回答
  • 2020-12-02 09:46

    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()
    
    0 讨论(0)
  • 2020-12-02 09:48

    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.

    0 讨论(0)
  • 2020-12-02 09:49
    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);
    
    0 讨论(0)
  • 2020-12-02 09:50

    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
      }
    });
    
    0 讨论(0)
  • 2020-12-02 09:50

    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

    0 讨论(0)
  • 2020-12-02 09:55

    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);
    
    0 讨论(0)
提交回复
热议问题