Accessing a font under assets folder from XML file in Android

后端 未结 14 1166
暖寄归人
暖寄归人 2020-12-05 17:07

I am trying to do a application-wide font change and creating a style file to do so. In this file (below) I just want to change typeface value of TextAppearance style of And

相关标签:
14条回答
  • 2020-12-05 18:11

    Instead of assets folder, you can put the .ttf file on fonts folder. To use fonts support in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26+. Right click res folder, new -> Android resource directory-> select font -> Ok. put your "myfont.ttf" file in newly created font folder.

    On res/values/styles.xml add,

    <style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/myfont</item>
    </style>
    

    On layout file add android:textAppearance="@style/customfontstyle",

    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="@style/customfontstyle"/>
    

    Refer : https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml

    0 讨论(0)
  • 2020-12-05 18:12

    Uses this function if you are using single font.

    public static void applyFont(final Context context, final View root, final String fontName) {
            try {
                if (root instanceof ViewGroup) {
                    ViewGroup viewGroup = (ViewGroup) root;
                    for (int i = 0; i < viewGroup.getChildCount(); i++)
                        applyFont(context, viewGroup.getChildAt(i), fontName);
                } else if (root instanceof TextView)
                    ((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontName));
            } catch (Exception e) {
                Log.e("ProjectName", String.format("Error occured when trying to apply %s font for %s view", fontName, root));
                e.printStackTrace();
            }
        }
    
    0 讨论(0)
提交回复
热议问题