14. public void setTypeface(){
15. typeFace = Typeface.createFromAsset(getAssets(), ”fonts/aaa.ttf”);
16. try
17. {
18. Field field = Typeface.class.getDeclaredField(“SERIF”);
19. field.setAccessible(true);
20. field.set(null, typeFace);
21. }
22. catch (NoSuchFieldException e)
23. {
24. e.printStackTrace();
25. }
26. catch (IllegalAccessException e)
27. {
28. e.printStackTrace();
29. }
30. }
31. }
public class App extends Application {
public static Typeface typeFace;
@Override
public void onCreate() {
super.onCreate();
//在app启动创建时调用
setTypeface();
}
/**
• 通过反射方法设置app全局字体
*/
public void setTypeface(){
typeFace = Typeface.createFromAsset(getAssets(), “fonts/aaa.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();
}
}
}
3、在manifest文件中配置application和主题
4、主题中加入<itemname=“android:typeface”>serif</item>
需要注意的的对于父主题的选择上,不要使用android:Theme.DeviceDefault开始的主题,因为这样就反射设置的字体就无法生效。
第二种,单个设置textview,这样比较的麻烦,textview有一个setTypeFace()方法,这样就能改变字体样式,这个方法不推荐使用。
第三种,比如说要所有的textview都要用第三方字体,那么就重写TextView,上面也说了textview有setTypeFace方法,将某人的字体替换成我们想要的就可以了。
[java] view plain copy
print ?
1. public class CusFntTextView extends TextView {
2. public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {
3. super(context, attrs, defStyle);
4. init();
5. }
6. public CusFntTextView(Context context, AttributeSet attrs) {
7. super(context, attrs);
8. init();
9. }
10. public CusFntTextView(Context context) {
11. super(context);
12. init();
13. }
14. private void init() {
15. if (!isInEditMode()) {
16. Typeface tf = Typeface.createFromAsset(getContext().getAssets(), ”Futura.ttf”);
17. setTypeface(tf);
18. }
19. }
public class CusFntTextView extends TextView {
public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();