I want to change AlertDialog
title color and background color without using custom layout. My requirement,
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>
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With