3 回答
TA貢獻1784條經驗 獲得超2個贊
好??!
這個問題已經很老了,但是如果有人(2015年)正在尋找有關如何通過xml代碼將自定義字體應用于所有Textview的答案,請直接參見以下內容:
首先:
我們需要在您的應用目錄中的assets文件夾內添加自定義字體:
.ttf或.otf都適用于Android
第二:
創建Class CustomTextView,它擴展了TextView,如下所示:
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setTypeface(Typeface tf) {
super.setTypeface(FontCache.getFont(getContext(),"fonts/<font_name>"));
}
}
第三:
在CustomTextView的setTypeface()方法中使用FontCache類,目的是使用HashMap進行基本的字體緩存:
public class FontCache {
private static Map<String,Typeface> fontMap = new HashMap<String,Typeface>();
public static Typeface getFont(Context context,String fontname){
if(fontMap.containsKey(fontname)){
return fontMap.get(fontname);
}
else{
Typeface tf = Typeface.createFromAsset(context.getAssets(),fontname);
fontMap.put(fontname,tf);
return tf;
}
}
}
第四: [最后一步]現在要做的就是在需要自定義字體textview的地方直接在XML文件中使用CustomTextView:
<<package_name>.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Font Text"
android:textSize ="18sp"
android:textAppearance="?android:textAppearanceSmall"
android:id="@+id/custom_txt"
/>
抱歉,如果此消息已發布在SO的某個位置。只是想分享一下是否有幫助!!
- 3 回答
- 0 關注
- 569 瀏覽
添加回答
舉報
