Home » Android » android – How to make an alert dialog with a spinner

android – How to make an alert dialog with a spinner

Posted by: admin June 15, 2020 Leave a comment

Questions:

I know how to make an alert dialog but I need to make one with a spinner so that when it pops up the person will have an option as to what happens. Does anyone have the code for an alert dialog with a spinner or know any good tutorials?

Thanks in advance

How to&Answers:
LayoutInflater li = LayoutInflater.from(context);

View promptsView = li.inflate(R.layout.my_dialog_layout, null);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

alertDialogBuilder.setView(promptsView);

// set dialog message

alertDialogBuilder.setTitle("My Dialog..");
alertDialogBuilder.setIcon(R.drawable.ic_launcher);
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();

final Spinner mSpinner= (Spinner) promptsView
        .findViewById(R.id.mySpinner);
final Button mButton = (Button) promptsView
        .findViewById(R.id.myButton);

// reference UI elements from my_dialog_layout in similar fashion

mSpinner.setOnItemSelectedListener(new OnSpinnerItemClicked());

// show it
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);

where

my_dialog_layout is the popup layout which you contains the Spinner mySpinner

EDIT :

public class OnSpinnerItemClicked implements OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent,
                View view, int pos, long id) {
            Toast.makeText(parent.getContext(), "Clicked : " +
                    parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();


        }

        @Override
        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    }