How to Set a Custom Font in the ActionBar Title?

后端 未结 17 1516
面向向阳花
面向向阳花 2020-11-22 09:46

How (if possible) could I set a custom font in a ActionBar title text(only - not the tab text) with a font in my assets folder? I don\'t want to use the android:logo option.

17条回答
  •  忘了有多久
    2020-11-22 10:18

    If you want to set typeface to all the TextViews in the entire Activity you can use something like this:

    public static void setTypefaceToAll(Activity activity)
    {
        View view = activity.findViewById(android.R.id.content).getRootView();
        setTypefaceToAll(view);
    }
    
    public static void setTypefaceToAll(View view)
    {
        if (view instanceof ViewGroup)
        {
            ViewGroup g = (ViewGroup) view;
            int count = g.getChildCount();
            for (int i = 0; i < count; i++)
                setTypefaceToAll(g.getChildAt(i));
        }
        else if (view instanceof TextView)
        {
            TextView tv = (TextView) view;
            setTypeface(tv);
        }
    }
    
    public static void setTypeface(TextView tv)
    {
        TypefaceCache.setFont(tv, TypefaceCache.FONT_KOODAK);
    }
    

    And the TypefaceCache:

    import java.util.TreeMap;
    
    import android.graphics.Typeface;
    import android.widget.TextView;
    
    public class TypefaceCache {
    
        //Font names from asset:
        public static final String FONT_ROBOTO_REGULAR = "fonts/Roboto-Regular.ttf";
        public static final String FONT_KOODAK = "fonts/Koodak.ttf";
    
        private static TreeMap fontCache = new TreeMap();
    
        public static Typeface getFont(String fontName) {
            Typeface tf = fontCache.get(fontName);
            if(tf == null) {
                try {
                    tf = Typeface.createFromAsset(MyApplication.getAppContext().getAssets(), fontName);
                }
                catch (Exception e) {
                    return null;
                }
                fontCache.put(fontName, tf);
            }
            return tf;
        }
    
        public static void setFont(TextView tv, String fontName)
        {
            tv.setTypeface(getFont(fontName));
        }
    }
    

提交回复
热议问题