亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Android中的自定義字體

Android中的自定義字體

智慧大石 2019-12-27 10:05:03
我已經閱讀了一些文章并在Google上進行了搜索,但是我沒有這樣做。我的問題是關于字體。在Android中,“ "android:typeface"Normal”,“ Sans”,“ Serif”,“ Monospace” 中只有4個屬性。那么,在應用程序中使用“ Verdana”該怎么辦?請建議我在Android應用程序中使用此字體的正確方法。
查看完整描述

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的某個位置。只是想分享一下是否有幫助!!


查看完整回答
反對 回復 2019-12-27
  • 3 回答
  • 0 關注
  • 569 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號