Use Roboto font for earlier devices

后端 未结 6 1050
说谎
说谎 2021-01-30 04:21

I would like to use the Roboto font in my Android application and make sure it works for earlier versions of Android that don\'t have the font installed. I know I can do this b

6条回答
  •  情歌与酒
    2021-01-30 05:00

    Above accepted answer is correct but I just wanted to supply my implementation here

    My utility class:

    package com.example.utils;
    
    import android.content.Context;
    import android.graphics.Typeface;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    
    public class AndroidUtils
    {
        private static Typeface robotoTypeFace;
    
        public static void setRobotoFont (Context context, View view)
        {
            if (robotoTypeFace == null)
            {
                robotoTypeFace = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
            }
            setFont(view, robotoTypeFace);
        }
    
        private static void setFont (View view, Typeface robotoTypeFace)
        {
            if (view instanceof ViewGroup)
            {
                for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++)
                {
                    setFont(((ViewGroup)view).getChildAt(i), robotoTypeFace);
                }
            }
            else if (view instanceof TextView)
            {
                ((TextView) view).setTypeface(robotoTypeFace);
            }
        }
    }
    

    How to use it, assuming this is an Activity:

    AndroidUtils.setRobotoFont(this, view);
    

    To set the same font to all the TextView you can use the decorView of your activity:

    ViewGroup godfatherView = (ViewGroup)this.getWindow().getDecorView();
    AndroidUtils.setRobotoFont(this, godfatherView);
    

    If you have adapters or fragments, don't forget to set their font as well.

    See here also.

提交回复
热议问题