1.首先要先知道Android中TextView设置字体样式的方法。
textView.setTypeface();// 设置字体样式如果要自定义字体样式,先在工程里新建一个assets目录,把自定义样式字体放在里面。
Typeface.createFromAsset(context.getAssets(), "fonts/Aileron-Light.otf");// 根据路径得到Typeface
问题是,怎么给Android应用设置全局自定义样式呢,如果每个textview都用setTypeface();方式设置的话,在listview中,会造成卡顿的现象。怎么解决呢?
首页在AndroidManifest.xml中 application中设置一个主题
<application android:name="com.qiyuan.congmingtou.app.CMTApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:persistent="true" android:label="@string/app_name" android:theme="@style/AppTheme">
在style.xml中
<style name="AppTheme" parent="AppBaseTheme"> <item name="android:windowNoTitle">true</item> <item name="android:typeface">serif</item></style>
Android中默认的字体样式有3中,
serif,
monospace,
sans,在style文件中,先随意指定一种。要记住你指定的字体样式。
3.写一个管理字体工具类FontsUtils
public class FontsUtils {private static Typeface cmtTypeFace; /*** 非中文内容使用此字体样式(设计需求)设置字体样式*/ public static void setCMTFonts(Context context, TextView textView) {textView.setTypeface(getCMTTypeface(context));// 设置字体样式 }/*** 非中文内容使用此字体样式(设计需求) 获取Typeface*/ public static Typeface getCMTTypeface(Context context) {if (cmtTypeFace == null) {cmtTypeFace = Typeface.createFromAsset(context.getAssets(),"fonts/Aileron-Light.otf");// 根据路径得到Typeface }return cmtTypeFace; }/*** 设置全局字体样式** @param context 上下文*/ public static void setAppTypeface(Context context) {try {Field field = Typeface.class.getDeclaredField("SERIF"); field.setAccessible(true); field.set(null, getCMTTypeface(context)); } catch (Exception e) {e.printStackTrace(); }}}用反射的机制,来设置字体的样式。这种方式有点暴力啊
Field field = Typeface.class.getDeclaredField("SERIF");getDeclaredField("")参数名是你在style里自己设置的默认字体样式"serif",这个使用单例模式,来获取Typeface实例。