How do I create an Android Spinner as a popup?

后端 未结 12 1781
梦如初夏
梦如初夏 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: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:

    
    
    
    
    

    Then, create the class:

    src/your/package/SpinnerDialog.java:

    public class SpinnerDialog extends Dialog {
        private ArrayList 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 list, DialogListener readyListener) {
            super(context);
            mReadyListener = readyListener;
            mContext = context;
            mList = new ArrayList();
            mList = list;
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.spinner_dialog);
            mSpinner = (Spinner) findViewById (R.id.dialog_spinner);
            ArrayAdapter adapter = new ArrayAdapter (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
      }
    });
    

提交回复
热议问题