做應用時,使用text顯現出的文字都屬於系統默認的字體,有時候達不到自己的需求
Android系統自帶了三種字體,分別是sans、serif和monospace,使用方式是在xml中配置typface即可
<TextView
android:id="@+id/header_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="24sp"
android:textStyle="bold"
android:typeface="sans"
android:textColor="@color/white" />
如果想使用其他的字體,可以按照如下方法:
首先下載想要顯示的字體的ttf文件,並且放到assets文件夾下的fonts文件夾中(fonts自己新建一個即可)
然後在代碼中設置控件的屬性即可:
// 使用自定義字體
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/YEGENYOUTEKAI9-28_0.TTF");
headerTextView.setTypeface(typeface);
將字體文件存放在assets文件夾中僅是一種方法,保存爲文件或者其他形式也能實現
如果想要將全部字體都更改,目前我所知道的辦法是遍歷所有控件,如果有更好的辦法,歡迎大家提供補充
public static void changeFonts(ViewGroup root, Activity activity) {
Typeface typeface = Typeface.createFromAsset(activity.getAssets(), "fonts/xxx.ttf");
for (int i = 0; i < root.getChildCount(); i++) {
View v = root.getChildAt(i);
if (v instanceof TextView) {
((TextView) v).setTypeface(typeface);
} else if (v instanceof Button) {
((Button) v).setTypeface(typeface);
} else if (v instanceof EditText) {
((EditText) v).setTypeface(typeface);
} else if (v instanceof ViewGroup) {
// 遞歸調用
changeFonts((ViewGroup) v, activity);
}
}
}