Friday, 28 March 2014

Customize AlertDialog buttons inside DialogFragment

When working with alert dialogs I was used to customize the positive and negative buttons appearance by retrieving them directly from the dialog after calling the show() method. (If you try to retrieve the buttons before the dialog is shown they will be null)
Just like this:

// Create the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton(R.string.btn_confirm_all, null);
builder.setNegativeButton(R.string.btn_cancel, null);
builder.setCancelable(false);
AlertDialog dialog = builder.create();
dialog.show();
// Retrieve the button
Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
// Customize the button
button.setTextColor(Color.WHITE);
button.setTypeface(Typeface.DEFAULT_BOLD);

Well, lately I started to use DialogFragment to embedd dialog lifecycle, the problem is that I didn't have direct access to the dialog anymore, I was just overriding the onCreateDialog() method:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Create the dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setPositiveButton(R.string.btn_confirm_all, null);
    builder.setNegativeButton(R.string.btn_cancel, null);
    builder.setCancelable(false);
    AlertDialog dialog = builder.create();
    return dialog;
}

The solution I found to customize the dialog button after show() was to store the just created dialog object in a global variable and then to retrieve it in the onResume() method of the DialogFragment:

@Override
public void onResume() {
     super.onResume();
     // Retrieve the button
     Button button = this.dialog.getButton(DialogInterface.BUTTON_POSITIVE);
     // Customize the button
     button.setTextColor(Color.WHITE);
     button.setTypeface(Typeface.DEFAULT_BOLD);
}

Hope it helps somebody!