Is it possible to set a custom font for entire of application?

后端 未结 25 2988
日久生厌
日久生厌 2020-11-22 02:44

I need to use certain font for my entire application. I have .ttf file for the same. Is it possible to set this as default font, at application start up and then use it else

25条回答
  •  无人共我
    2020-11-22 03:22

    I would like to improve weston's answer for API 21 Android 5.0.

    Cause

    Under API 21, most of the text styles include fontFamily setting, like:

    
    

    Which applys the default Roboto Regular font:

    sans-serif
    

    The original answer fails to apply monospace font, because android:fontFamily has greater priority to android:typeface attribute (reference). Using Theme.Holo.* is a valid workaround, because there is no android:fontFamily settings inside.

    Solution

    Since Android 5.0 put system typeface in static variable Typeface.sSystemFontMap (reference), we can use the same reflection technique to replace it:

    protected static void replaceFont(String staticTypefaceFieldName,
            final Typeface newTypeface) {
        if (isVersionGreaterOrEqualToLollipop()) {
            Map newMap = new HashMap();
            newMap.put("sans-serif", newTypeface);
            try {
                final Field staticField = Typeface.class
                        .getDeclaredField("sSystemFontMap");
                staticField.setAccessible(true);
                staticField.set(null, newMap);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            try {
                final Field staticField = Typeface.class
                        .getDeclaredField(staticTypefaceFieldName);
                staticField.setAccessible(true);
                staticField.set(null, newTypeface);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题