In this class we see how to show an alert dialog with buttons. AlertDialog allows us display simple dialogs without us creating any layout.

Our alert dialog in this case will have two buttons: a positive button and a negative button.

 

AlertDialog with Buttons

We then handle the onClick events for these buttons.

1. Create Project

In your android studio create an empty activity. If you are not sure how to do that check this tutorial.

In our generated project we will have one class: MainActivity and one layout activity_main.xml.

3. activity_main.xml

First we will have our layouts here.
This layout will get inflated into our activity.

At the root we have relativelayout. We add our TextView as well as a button inside the layout.

When the button is clicked we will display our alertdialog with buttons.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    tools_context="info.camposha.mysimplealertdialogbuttons.MainActivity">

    <TextView
        android_id="@+id/headerLabel"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_alignParentTop="true"
        android_layout_centerHorizontal="true"
        android_fontFamily="casual"
        android_text="Simple AlertDialog Buttons"
        android_textAllCaps="true"
        android_textSize="24sp"
        android_textStyle="bold" />

    <Button
        android_id="@+id/showAlertID"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_text="Show Alert Dialog"
        android_layout_centerHorizontal="true"
        android_layout_centerVertical="true"
    />

</RelativeLayout>

3. MainActivity.java

Here’s our main activity code:

package info.camposha.mysimplealertdialogbuttons;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/*
ANDROID ALERTDIALOG WITH BUTTONS
 */
public class MainActivity extends Activity {
    /*
     ONCREATE METHOD
      */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //REFERENCE BUTTON AND SHOW IT.
        Button showBtn=findViewById(R.id.showAlertID);
        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlert();
            }
        });
    }
    /*
    CREATE AN ALERT DIALOG AND SHOW IT
     */
    private void showAlert()
    {
        //initialize alertdialog
        AlertDialog myDialog = null;

        //INSTANTIATE ALERTDIALOG BUILDER
        AlertDialog.Builder myBuilder=new AlertDialog.Builder(this);
        myBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "OK clicked", Toast.LENGTH_SHORT).show();
            }
        });
        //final dialog
        final AlertDialog finalDialog = myDialog;
        myBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finalDialog.dismiss();
            }
        });
        //SET PROPERTIES USING METHOD CHAINING
        myBuilder.setTitle("Science Tips").setMessage("Boomerang Nebular is the Coldest region in the Universe");
        //CREATE DIALOG
        myDialog=myBuilder.create();
        //SHOW DIALOG
        myDialog.show();
    }
}

Notes

  1. First we specify the package for our application.
    package info.camposha.mysimplealertdialogbuttons;
  2. Then add our import statements.
  3. Then we create our class called MainActivity and make it derive from android.app.Activity.
    public class MainActivity extends Activity {..}
  4. We’ll create a method called showAlert() that will create our dialog using the AlertDialog.Builder class and then add the buttons. To add the button we use the setPositiveButton() and setNegative() methods. These methods are defined in the AlertDialog.Builder class. We also set the title and message of the dialog using methods defined in the same class.
  5. We finally override the onCreate() method and show the alert dialog when the showBtn button is clicked.

Quick AlertDialog Examples

1. One static method you can reuse

You can reuse this to quickly create your alertdialogs with buttons.

It’s static so you don’t need a class instance. All you need is pass a Context object as well as you custom title and message.

    public static void createInformativeDialog(Context context, String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message)
                .setCancelable(true)
                .setPositiveButton(context.getResources().getString(R.string.action_ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }