Android: How can I change AlertDialog Title Text Color and Background Color without using custom layout?

You can use custom title to your alert dialog:

TextView textView = new TextView(context);
textView.setText("Select an option");
textView.setPadding(20, 30, 20, 30);
textView.setTextSize(20F);
textView.setBackgroundColor(Color.CYAN);
textView.setTextColor(Color.WHITE);

final CharSequence[] items = {"Visiting Card", "Prescription Letter"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCustomTitle(textView);
builder.setItems(items, (dialog, item) -> {
    }).show();

Custom Alert Dialog Header

check sample image

You can change color of alert dialog title, background and button color by using custom theme.

   <style name="CustomDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert"> 
        <item name="android:windowBackground">@android:color/black</item>
        <item name="colorAccent">@android:color/white</item>
        <item name="android:textColorPrimary">@android:color/white</item>
    </style>

android: windowBackground to change background color

colorAccent to change button color

android:textColorPrimary to change Dialog title color

apply this theme to dialog

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.CustomDialogTheme);

You can change everything in the alert dialog:

// Title
TextView titleView = new TextView(context);
titleView.setText("Title");
titleView.setGravity(Gravity.CENTER);
titleView.setPadding(20, 20, 20, 20);
titleView.setTextSize(20F);
titleView.setTypeface(Typeface.DEFAULT_BOLD);
titleView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
titleView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

AlertDialog ad = new AlertDialog.Builder(context).create();

ad.setCustomTitle(titleView);

ad.setCancelable(false);

ad.setMessage("Message");

ad.setButton(Dialog.BUTTON_POSITIVE,"OK",new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // your code
    }
});

ad.show();

// Message
TextView messageView = ad.findViewById(android.R.id.message);

if (messageView != null) {
    messageView.setGravity(Gravity.CENTER);
}

// Buttons
Button buttonOK = ad.getButton(DialogInterface.BUTTON_POSITIVE);
buttonOK.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));

Leave a Comment