Android全局更换字体

在main/assets中添加字体文件

Android全局更换字体_第1张图片
Paste_Image.png
 public static Typeface typeface;

 /**
 * 初始化字体:苹方
 */
private void initTypeFace() {
    if (typeface == null) {
        typeface = Typeface.createFromAsset(getAssets(), "PingFang-Regular.ttf");
    }

    LayoutInflaterCompat.setFactory(LayoutInflater.from(this), new LayoutInflaterFactory() {
        @Override
        public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
            AppCompatDelegate delegate = getDelegate();
            View view = delegate.createView(parent, name, context, attrs);

            if (view != null && (view instanceof TextView)) {
                ((TextView) view).setTypeface(typeface);
            }
            return view;
        }
    });
}

注意:initTypeFace 要写在onCreate方法的super.onCreate(savedInstanceState);之前

你可能感兴趣的:(Android全局更换字体)