How to create AlertDialog in Android Studio

STEP 1:

To create an Alert Dialog we need to create an instance of Alert.Dialog builder with the default Theme (R.attr.alertDialogTheme).

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

STEP 2:

Now we have to add Title,positive Button,negative Button.We dont have to edit XML file because we use just standart default  “Window” with defined Views. Dont forget to add an anonymous on Click Method to use the Listener.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                this);
        alertDialogBuilder.setTitle(Html.fromHtml(
                "<font color='black'>"+"Step 1"+"</font>"));
        alertDialogBuilder
                .setMessage("Do you want to continue?")
                .setCancelable(false)
                .setNegativeButton(Html.fromHtml("<font color='red'>"+"NO"+"</font>"),new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing


                        dialog.cancel();
                    }
                })
                .setPositiveButton(Html.fromHtml("<font color='black'>"+"yes"+"</font>"),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Context context = getApplicationContext();
                                CharSequence text = "Alright we continue";
                                int duration = Toast.LENGTH_SHORT;

                                Toast toast = Toast.makeText(context, text, duration);
                                toast.show();

                            }

                        });

STEP 3:

The last step is to create Alertdialog constructor and start it.

 
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

Leave a Reply

Your email address will not be published. Required fields are marked *