是新的Android開發我需要爲整個應用程序自定義字體爲我寫了:如何更改棒棒糖版本以上的Android應用程序的默認字體?
public class TypeFaceUtil {
public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Map<String, Typeface> newMap = new HashMap<String, Typeface>();
newMap.put("SERIF", customFontTypeface);
try {
final Field staticField = Typeface.class
.getDeclaredField("sSystemFontMap");
staticField.setAccessible(true);
staticField.set(null, newMap);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
try {
final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
defaultFontTypefaceField.setAccessible(true);
defaultFontTypefaceField.set(null, customFontTypeface);
} catch (Exception e) {
Log.e(TypeFaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
}
}
}
}
,我把它叫做應用程序類是這樣的:
public class tt extends Application {
@Override
public void onCreate() {
super.onCreate();
TypeFaceUtil.overrideFont(getApplicationContext(),"SERIF","fonts/calibri.ttf");
}
}
我的字體是不在棒棒糖或以上版本工作,我也嘗試這種方法Custom Fonts not working in lollipop?如何創建一個支持所有版本的自定義字體提前謝謝
除非通過調用textview,button或其他視圖的setTypeface()方法來設置字體,否則字體將不會「工作」。 – Talha
@ M.Yogeshwaran看到我的回答 –