Override Button of AlertDialog – Android

Home / Android / Override Button of AlertDialog – Android

As per the requirement of applications, sometimes we need to provide a custom feature to the buttons of AlertDialog. For instance, we may need to change the color of Positive, Negative, and/or Neutral buttons. And for the same reason, we may need to override button of AlertDialog to provide custom behavior.

In this tutorial, we are going to override the buttons of AlertDialog. So, this tutorial covers following points.
– Create AlertDialog
– Override the Buttons of AlertDialog
– Change text color of AlertDialog buttons

Create Android Application Project

If you are new to Android Studio, then you could learn about creating new projects from our tutorial Create Android Application Project in Android Studio Continued.

Create Android application project with following attributes.

Project Name AlertButtonOverride
Package Name com.pcsalt.example.alertbuttonoverride
Minimum SDK Version 19
Activity Type Empty Activity
Activity Name MainActivity
Layout Name activity_name




Prepare layout screen

activity_main.xml: Layout for MainActivity.java. For this demo application, we need a Button only. Instead of using findViewById() for this button, we are binding buttonClicked with ClickListener of Button.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="buttonClicked"
        android:text="Hello World!" />
</RelativeLayout>

Create AlertDialog

Now, Android provides AlertDialog in two packages.
– android.app.AlertDialog
– android.support.v7.app.AlertDialog

android.app.AlertDialog: The dialogs created using this class, will display dialog specific to the API level of the device. For KitKat it will display native AlertDialog, and same code will display material AlertDialog in Lollipop and above devices.
android.support.v7.app.AlertDialog: This class will generate material AlertDialog for all API level of the device. We will be using this class to create and display AlertDialog. No additional action is needed to use this class.

public void buttonClicked(View view) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    dialogBuilder.setTitle("Demo");
    dialogBuilder.setMessage("After clicking the \"Done\" button, dialog will not close.");
    dialogBuilder.setPositiveButton("Done", null);
    dialogBuilder.setNegativeButton("Close", null);

    final AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

    Button positiveButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
    // override the text color of positive button
    positiveButton.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
    // provides custom implementation to positive button click
    positiveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onPositiveButtonClicked(alertDialog);
        }
    });

    Button negativeButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
    // override the text color of negative button
    negativeButton.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
    // provides custom implementation to negative button click
    negativeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNegativeButtonClicked(alertDialog);
        }
    });

}

NOTE: Always override AlertDialog Button after calling AlertDialog.show() method. Otherwise, it will throw NullPointerException while adding ClickListener to the overriden button.

In this method buttonClicked, we are creating an AlertDialog with a title, message, and two buttons. Then, after calling AlertDialog.show(), we are overriding button of AlertDialog for:
– Custom action on button click, and
– Change text color of the button text.

MainActivity.java

Here is the complete code of MainActivity.java with imports and onPositiveButtonClicked() and onNegativeButtonClicked().

package com.pcsalt.example.alertbuttonoverride;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /*
    This method is referenced from Button in activity_main.xml
     */
    public void buttonClicked(View view) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Demo");
        dialogBuilder.setMessage("After clicking the \"Done\" button, dialog will not close.");
        dialogBuilder.setPositiveButton("Done", null);
        dialogBuilder.setNegativeButton("Close", null);

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        Button positiveButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        // override the text color of positive button
        positiveButton.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
        // provides custom implementation to positive button click
        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPositiveButtonClicked(alertDialog);
            }
        });

        Button negativeButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        // override the text color of negative button
        negativeButton.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        // provides custom implementation to negative button click
        negativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNegativeButtonClicked(alertDialog);
            }
        });

    }

    private void onPositiveButtonClicked(AlertDialog alertDialog) {
        Toast.makeText(MainActivity.this, "Dialog will NOT close", Toast.LENGTH_SHORT).show();
    }

    private void onNegativeButtonClicked(AlertDialog alertDialog) {
        Toast.makeText(MainActivity.this, "Dialog will close now", Toast.LENGTH_SHORT).show();
        alertDialog.dismiss();
    }
}

Screenshots:

Override button AlertDialog 1 Override button of AlertDialog 1

Download Source Code

Download Source Code

Video tutorial: