最近有個需求要修改android app默認字體。網上有很多方法,但是最坑的是都沒有效果,但是最後還是解決了,不過不知道是什麼原因,如果知道的話歡迎留言(謝謝大家)
解決方案:
添加字體(.ttf)到工程目錄assets下, 我的是在assets在新建了一個fonts包。注意assets是和java包同級的
修改字體的代碼:工具類FontsOverride:
public final class FontsOverride {
public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) {
try {
final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
全局在BaseApplication裏面使用:
@Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "SANS_SERIF", "fonts/PingFang-ExtraLight.ttf");
}
上面的代碼寫好運行後,會發現沒有效果。在一個偶然情況下 我在style的AppThem裏面添加了TextView的typeface屬性具體:
<!-- Base application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- Customize your theme here. -->
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:typeface">sans</item>
</style>
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
</style>
注意裏面的
<item name="android:typeface">sans</item>
大家都知道typeface有幾個屬性值:
- noraml (普通字體,系統默認使用的字體)
- sans(非襯線字體)
- serif (襯線字體)
- monospace(等寬字體)
我試過如果把sans改成另外三個,自己更改的字體是沒有效果的,只有在sans的情況下更改自己的字體纔會顯示效果,不知道是上面原因,求告知。我是在android 4.4.4的版本測試的,最奇怪的就是單個設置字體又有效果。。。
單個設置字體代碼:
private Typeface typeface;
TextView mContent;
typeface = Typeface.createFromAsset(getAssets(), "fonts/PingFang-Light.ttf");
mContent.setTypeface(typeface);
最後 很無解 希望大家可以留言告訴我,謝謝大家(⊙﹏⊙)(⊙﹏⊙)(⊙﹏⊙)(⊙﹏⊙)(⊙﹏⊙)(⊙﹏⊙)(⊙﹏⊙)(⊙﹏⊙)