Knowband Blog | Ecommerce Modules

How to Create Alert Dialog box in Android?

The alert dialog box can be used to display a message in a popup dialog box or display a text field for user input or show any custom view in the dialog box.

For the view to be displayed in the popup dialog, the view has to be created programmatically or via XML. Then the view has to be set in the dialog so that this view is visible to the user in the dialog box.

Find the steps below to create a dialog box in which there will be a field for user input.

1. Create a view to be displayed in the dialog box.

final EditText userInput = new EditText(this);

2. Creating and displaying a dialog box.

new AlertDialog.Builder(this)
                .setTitle(“Title of the dialog box goes here”)
                .setView(userInput)
                .setPositiveButton(“Submit”, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Handle your action here when “Submit” button is clicked
                    }
                })
                .setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
		// Handle your action here when “Cancel” button is clicked 
                    }
                })
                .show();