準備字體文件
創建目錄 src/main/assets/fonts/,然后把你的字體文件拷貝到這個目錄下,Android支持 .ttf (TrueTypeFont) or .otf (OpenTypeFont) 這兩種格式。
假設我們有這樣一個TextView引用
TextView tvText = (TextView)findViewById(R.id.tvText);
方法一:
// 創建一個 TypeFace
Typeface mtypeFace = Typeface.createFromAsset(getAssets(),"fonts/MyFont.ttf");
// 為目標控件設置TypeFace
tvText.setTypeface(mtypeFace);
這種方法需要為所有需要使用自定義字體的TextView /Button /EditText 設置字體,如果你有大量的需要使用自定義字體的控件,這顯然不是明智的選擇,那么也許你需要方法二。
方法二:
創建一個自定義TextView,然后在XML文件中直接使用(當然你也可以自定義Button /EditText,道理是一樣的)。
public class CustomTextView extends TextView {
private static final String TAG = "CustomTextView";
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
String customFont = a.getString(R.styleable.CustomTextView_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface typeface = null;
try {
typeface = Typeface.createFromAsset(ctx.getAssets(),"fonts/"+asset);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
這個自定義TextView有一個自定義屬性,所以你需要在你的values/attrs.xml(若沒有則創建這樣一個文件)文件中添加如下內容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextView">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
自定義TextView創建完畢,現在開始在XML文件中使用。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.jdqm.CustomTextView
android:id="@+id/tv_custom"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="@string/sample_text"
app:customFont="my_font.otf">
</com.jdqm.CustomTextView>
</LinearLayout>
關注微信公眾號,第一時間接收推送!