自定義TextView匯入外部特殊字型
阿新 • • 發佈:2019-01-22
前段時間由於專案需求,app需要使用特殊字型,所以在網上搜颳了一大波部落格把需求完成了,但是由於並沒有完美的解決問題(問題見上篇部落格),幾經曲折跟好基友請教了一番,毛瑟頓開,才有了一下這篇博文。
特殊字型包的匯入請見上篇文章,這裡就不在贅述了。接下來貼程式碼:
先是自定義一個textview為了接下來存放外部特殊字型,檔案目錄如下:
CustomTextView類檔案:
package com.example.administrator.customview;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by Administrator on 2016-06-02.
* 自定義 TextView
*/
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super (context, attrs);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defSyle) {
super(context, attrs, defSyle);
init(context);
}
/***
* 設定字型
*
* @return
*/
public void init(Context context) {
setTypeface(FontCustom.setFont(context));
}
}
FontCustom類檔案:
package com.example.administrator.customview;
import android.content.Context;
import android.graphics.Typeface;
/**
* Created by Administrator on 2016-06-02.
* 特殊字型定義
*/
public class FontCustom {
static String fongUrl = "font/FangZhen_GBK.ttf";
static Typeface tf;
/***
* 設定字型
*
* @return
*/
public static Typeface setFont(Context context) {
if(tf==null){
tf = Typeface.createFromAsset(context.getAssets(), fongUrl);
}
return tf;
}
}
ok,自定義textview完成,接下來就是在xml佈局裡邊呼叫,直接改變TextView標籤就可以了:
<customview.CustomTextView
android:id="@+id/UserCenter_txt"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="2dp"
android:layout_weight="6"
android:text="@string/UserCenter_txt"
/>
完成了這些操作以後,就可以執行你的專案看看效果了,不用像上篇部落格一樣一個一個TextView控制元件去stetType()了,(笑哭……)!
執行後的效果圖:
是不是完美解決了,系統字型字號過大就變粗的硬傷。