修改 字体
例子一:
快速修改整个页面所有的字体
将字体文件放在assets文件夹中的fonts文件夹之下;
首先编写一个工具类:
package com.example.m_evolution.Utils; import android.app.Activity; import android.graphics.Typeface; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class FontManager { public static void changeFonts(ViewGroup root, Activity act) { Typeface tf = Typeface.createFromAsset(act.getAssets(), "fonts/pingfang_light.ttf"); for (int i = 0; i < root.getChildCount(); i++) { View v = root.getChildAt(i); if (v instanceof TextView) { ((TextView) v).setTypeface(tf); } else if (v instanceof Button) { ((Button) v).setTypeface(tf); } else if (v instanceof EditText) { ((EditText) v).setTypeface(tf); } else if (v instanceof ViewGroup) { changeFonts((ViewGroup) v, act); } } } }
思路,遍历ViewGroup中所有的子项,如果是TextView等控件就修改其字体,注意有可能子项也是ViewGroup;
接着在Activity中调用:
FontManager.changeFonts((ViewGroup) getWindow().getDecorView(),this);
例子二:
修改整个APP的字体
在Application类中用自带的字体替换系统的serif字体:
//修改字体 Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/pingfang_light.ttf"); try { Field field = Typeface.class.getDeclaredField("SERIF"); field.setAccessible(true); field.set(null, typeface); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }
然后在style.xml中配置App的样式:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:typeface">serif</item> </style>