Theme not applying to DialogFragment on Android

luthier picture luthier · May 14, 2012 · Viewed 36.8k times · Source

I'm switching my old Dialogs to DialogFragment, but the themes and styles don't seem to be working.

I'm using the DialogFragment from the compatibility library v4, and in the onCreate method I've tried calling setStyle(style, theme); with a lot of different themes, but the dialog always shows as an "old" dialog in the emulator running Android 4.0.3 (i.e., it does not shows in Holo theme).

Is there anything else that I should be doing? Does using the compatibility library disables the Holo theme or anything? If this is the case, should I create two DialogFragments, one for older versions and one for newer versions?

Thanks!


Here's the (simplified) code for my dialog. I've tried both Theme_Holo_Dialog_NoActionBar and Theme_DeviceDefault_Dialog_NoActionBar, but the Android 4 emulator always shows the dialog as an "old" dialog instead of using the Holo theme. What am I doing wrong? :(

[...]
import android.support.v4.app.DialogFragment;
[...]

public class AlertDialogFragment extends DialogFragment {

  public static AlertDialogFragment newInstance(int id) {

    AlertDialogFragment f = new AlertDialogFragment();
    Bundle args = new Bundle();
    args.putInt("id", id);
    f.setArguments(args);

 }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int style = DialogFragment.STYLE_NORMAL, theme = 0;
    theme = android.R.style.Theme_Holo_Dialog_NoActionBar;
    setStyle(style, theme);     
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {

    mId = getArguments().getInt("id");
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
        .setTitle(mTitle)
        .setMessage(mMessage)
        .setPositiveButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {      
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismiss();                  
            }
        });
        return builder.create();
    }

Answer

Florian picture Florian · Dec 13, 2012

You shoudn't use the AlertDialog.Builder(Context, int) constructor with the support library because it is only available since API 11.

To setup a theme to your dialog, use instead a ContextThemeWrapper like this:

ContextThemeWrapper context = new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Dialog_NoActionBar);
AlertDialog.Builder builder = new AlertDialog.Builder(context);