Issue
I have many alert dialogs in my app. It is a default layout but I am adding positive and negative buttons to the dialog. So the buttons get the default text color of Android 5 (green). I tried to changed it without success. Any idea how to change that text color?
public class MyCustomDialog extends AlertDialog.Builder {
public MyCustomDialog(Context context,String title,String message) {
super(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View viewDialog = inflater.inflate(R.layout.dialog_simple, null, false);
TextView titleTextView = (TextView)viewDialog.findViewById(R.id.title);
titleTextView.setText(title);
TextView messageTextView = (TextView)viewDialog.findViewById(R.id.message);
messageTextView.setText(message);
this.setCancelable(false);
this.setView(viewDialog);
} }
Creating the dialog:
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage);
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
...
}
}).show();
That negativeButton is a default dialog button and takes the default green color from Android 5 Lollipop.
Many thanks
Solution
You can try to create the AlertDialog
object first, and then use it to set up to change the color of the button and then show it. (Note that on builder
object instead of calling show()
we call create()
to get the AlertDialog
object:
//1. create a dialog object 'dialog'
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage);
AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
...
}
}).create();
//2. now setup to change color of the button
dialog.setOnShowListener( new OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(COLOR_I_WANT);
}
});
dialog.show()
The reason you have to do it on onShow()
and cannot just get that button after you create your dialog is that the button would not have been created yet.
I changed AlertDialog.BUTTON_POSITIVE
to AlertDialog.BUTTON_NEGATIVE
to reflect the change in your question. Although it is odd that "OK" button would be a negative button. Usually it is the positive button.
Answered By - trungdinhtrong
Answer Checked By - Gilberto Lyons (JavaFixing Admin)