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

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

自定義字體和XML布局(Android)

自定義字體和XML布局(Android)

翻閱古今 2019-06-27 16:41:05
自定義字體和XML布局(Android)我試圖在Android中使用XML文件定義GUI布局。據我所知,沒有辦法指定您的小部件應該在XML文件中使用自定義字體(例如,您在資產/字體/中放置的字體),而且您只能使用已安裝的系統字體。我知道,在Java代碼中,我可以使用唯一的ID手動更改每個小部件的字體?;蛘?,我可以迭代Java中的所有小部件來進行此更改,但這可能會非常慢。我還有別的選擇嗎?有什么更好的方法來制作具有自定義外觀的小部件嗎?我并不特別想手動更改我添加的每個新小部件的字體。
查看完整描述

3 回答

?
largeQ

TA貢獻2039條經驗 獲得超8個贊

這可能有點晚,但您需要創建一個返回自定義字體的單例類,以避免內存泄漏。

字體類:

public class OpenSans {private static OpenSans instance;private static Typeface typeface;public static OpenSans getInstance(Context context) {
    synchronized (OpenSans.class) {
        if (instance == null) {
            instance = new OpenSans();
            typeface = Typeface.createFromAsset(context.getResources().getAssets(), "open_sans.ttf");
        }
        return instance;
    }}public Typeface getTypeFace() {
    return typeface;}}

自定義TextView:

public class NativelyCustomTextView extends TextView {

    public NativelyCustomTextView(Context context) {
        super(context);
        setTypeface(OpenSans.getInstance(context).getTypeFace());
    }

    public NativelyCustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTypeface(OpenSans.getInstance(context).getTypeFace());
    }

    public NativelyCustomTextView(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
        setTypeface(OpenSans.getInstance(context).getTypeFace());
    }}

通過XML:

<com.yourpackage.views.NativelyCustomTextView
            android:id="@+id/natively_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_margin="20dp"
            android:text="@string/natively"
            android:textSize="30sp" />

以編程方式:

TextView programmaticallyTextView = (TextView) 
       findViewById(R.id.programmatically_text_view);programmaticallyTextView.setTypeface(OpenSans.getInstance(this)
                .getTypeFace());


查看完整回答
反對 回復 2019-06-27
  • 3 回答
  • 0 關注
  • 833 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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