Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a custom font in an AlertDialog using Support Library 26

I am using revision 26.0.1 of the Android Support Library to set custom fonts in my app. In my app's theme, I added:

<item name="android:fontFamily">@font/my_font</item>

It worked like a charm, converting the text in my whole app to my custom font. EXCEPT for my dialogs - specifically their titles, messages, and also their NumberPickers. In those places, fonts were not updated. (Radio buttons and checkboxes worked; so did the yes/no buttons)

Is there something I'm forgetting to add to my themes or styles? Or is this simply not supported yet by the support library?

A little more detail: I am using AppCompatDialogFragment to implement all my dialogs. In their onCreateDialog() methods, I create a dialog using AlertDialog.Builder then return it.

Thanks for the help!

like image 307
yuval Avatar asked Aug 17 '17 03:08

yuval


People also ask

How do I change the font in AlertDialog?

If you only want to change text format, you can just override alertDialogTheme attribute to change the theme for the AlertDialog . <style name="MyTheme" parent="Theme. AppCompat. Light.

How do I add custom fonts to my Samsung?

From Settings, search for and select Font size and style. Then, tap Font size and style again. Tap Font style, and then tap + Download fonts. The Galaxy Store will automatically launch; tap the Install icon next to your desired font.


1 Answers

Thank you everybody who answered, but unfortunately none of those solutions worked for me. I hope they will work for someone else.

I've concluded that this is a bug in the support library, and hopefully Google will fix. In the meantime, I developed this hacky workaround:

public static void applyCustomFontToDialog(Context context, Dialog dialog) {
    Typeface font = ResourcesCompat.getFont(context, R.font.my_font);
    if (font != null) {
        TextView titleView = dialog.findViewById(android.support.v7.appcompat.R.id.alertTitle);
        TextView messageView = dialog.findViewById(android.R.id.message);
        if (titleView != null) titleView.setTypeface(font, Typeface.BOLD);
        if (messageView != null) messageView.setTypeface(font);
    }
}

This works by scanning the dialog's view tree for the title and message views by the IDs that the support library gives them. If the support library were to change these IDs, this would no longer work (which is why it's hacky). Hopefully Google fixes this issue and I won't need to do this anymore.

like image 78
yuval Avatar answered Sep 22 '22 06:09

yuval