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

Sagar Zala picture Sagar Zala · Jul 17, 2018 · Viewed 13.7k times · Source

I want to change AlertDialog title color and background color without using custom layout. My requirement,

I want like this

I tried below code, but can't work.

final CharSequence[] items = {" Visiting Card", "Prescription Letter"};
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setMessage(message)
            .setTitle(title).setCancelable(false);

    builder.setItems(items, (dialog, item) -> {
    });

    AlertDialog dialog = builder.create();
            dialog.show();
    int textViewId = dialog.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
    TextView tv = dialog.findViewById(textViewId); // It always returns null
    if (tv != null) {
        tv.setTextColor(activity.getResources().getColor(R.color.white));
        tv.setBackgroundColor(activity.getResources().getColor(R.color.colorPrimary));
}

Using below lines I tried but it always returns null in findViewById,

int textViewId = dialog.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
TextView tv = dialog.findViewById(textViewId);

I also tried using style but it only change Title text color,

<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:background">#ffffff</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:headerBackground">@color/colorPrimary</item>
</style>

Answer

Anisuzzaman Babla picture Anisuzzaman Babla · Jul 17, 2018

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