Android自定义字体

设置自定义字体

这里只是其中一种方法,相信,应该还有跟多的方法实现效果。

下面的方法是通过代码来完成。

我们可以在程序中放入ttf字体文件,在程序中使用Typeface设置字体。
第一步,在assets目录下新建fonts目录,把ttf字体文件放到fonts文件夹下面。
第二步,程序中调用:
AssetManager mgr=getAssets();
Typeface tf=Typeface.createFromAsset(mgr, "fonts/bmzy.ttf");

tv=findViewById(R.id.textview);

tv.setTypeface(tf);

原始字体和自定义字体效果预览

  VS  

至此该控件设置自定义字体完成。


设置全局自定义字体

首先在style.xml中定义一个主题样式。

    <style name="AppTheme" parent="AppBaseTheme">
            <item name="android:windowNoTitle">true</item>
    <item name="android:typeface">monospace</item>
    <item name="android:windowBackground">@android:color/transparent</item>
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->

    </style>

然后在AndroidManifest.xml中 application中使用这个主题

    <application
        android:name="com.bd.application.TestApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

其次

自定义TestApplication继承Application

在TestApplication的oncreate()方法中通过反射修改APP默认字体

代码如下

public class TestApplication extends Application {

private static TestApplication mSelf;
String fontPath = "fonts/bmzy.ttf";

@Override
public void onCreate() {
super.onCreate();
mSelf = this;
replaceSystemDefaultFont(this, fontPath);
}
public static TestApplication getInstance() {
return mSelf;
}
public void replaceSystemDefaultFont(Context context, String fontPath) {

        /* 因为我们在主题里给app设置的默认字体就是monospace所以這里我们修改的是MoNOSPACE,设置其他的也可以,但是需要注意的是必须保持设置和修改的一致。(Android中默认的字体样式有serif monospace   等)*/

replaceTypefaceField("MONOSPACE", createTypeface(context, fontPath));
}
// 通过字体资源地址创建自定义字体
private Typeface createTypeface(Context context, String fontPath) {
return Typeface.createFromAsset(context.getAssets(), fontPath);
}
// 修改MONOSPACE字体为自定义的字体达到修改app默认字体的目的
private void replaceTypefaceField(String fieldName, Object value) {
try {
Field field = Typeface.class.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(null, value);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}


猜你喜欢

转载自blog.csdn.net/niu9799/article/details/80736966