廢話不說,下面是代碼:
package com.windy.androidfont; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; public class FontTextView extends TextView { private Context mContext; private String TypefaceName = ""; public String getTypefaceName() { return TypefaceName; } public void setTypefaceName(String typefaceName) { TypefaceName = typefaceName; Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "font/" + TypefaceName + ".ttf"); this.setTypeface(typeface); System.gc(); } public FontTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.mContext = context; int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0); if (resouceId != 0) { TypefaceName = context.getResources().getString(resouceId); } else { TypefaceName = attrs.getAttributeValue(null, "typefaceName"); } if (TypefaceName != null && !"".equals(TypefaceName)) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf"); this.setTypeface(typeface); } } public FontTextView(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; // 先判斷是否配置的資源文件 int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0); if (resouceId != 0) { TypefaceName = context.getResources().getString(resouceId); } else { TypefaceName = attrs.getAttributeValue(null, "typefaceName"); } if (TypefaceName != null && !"".equals(TypefaceName)) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf"); this.setTypeface(typeface); } } public FontTextView(Context context) { super(context); this.mContext = context; // TypefaceName = attrs.getAttributeValue(null, "TypefaceName"); if (TypefaceName != null && !"".equals(TypefaceName)) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf"); this.setTypeface(typeface); } } }
下面是布局:
<com.example.androidfont.FontTextView android:id="@+id/fontTextView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="69dp" typefaceName="pop" android:text="FontTextView" android:textSize="30sp" />
大字體是要設置的屬性,pop是字體庫的名字
注意:自體庫文件我這里放到了assets中的font文件夾中給個截圖吧:
strings.xml文件中的截圖:可以把字體的配置放到字符串資源中,這樣就能統一進行更改了,如果你的需要中要動態的進行配置的話,可以對FontTextView進行改寫,我的想法是在將自體配置放進prefrence中進行配置,這樣就可以直接在FontTextView中進行改寫了,本來想把這個類寫的完成呢,由於時間關系就沒寫,有需求的可以自己去實現。就說這么多吧。
有需要代碼的可以發郵件到我的郵箱:545099227@qq.com(QQ:545099227)