簡體   English   中英

將TextView設置為帶有xml屬性和自定義字體的粗體字體(不起作用)

[英]Setting TextView to bold font with xml-attribute and custom font (not working)

我正在構建一個應用程序,我們正在使用一種自定義字體Apercu,您可能聽說過。 無論如何,我已經構建了一個實用程序來幫助我在所有元素上設置字體。

這就是該util中的方法之一(我也有在ViewGroup上設置此字體的方法,在其中我遍歷所有元素):

public static void setApercuOnTextView(final TextView view, final Context context) {
    Typeface tmpTypeface = apercu;
    Typeface tmpTypefaceBold = apercuBold;

    if (tmpTypeface == null && tmpTypefaceBold == null) {
        apercu = Typeface.createFromAsset(context.getAssets(), "fonts/Apercu.otf");
        apercuBold = Typeface.createFromAsset(context.getAssets(), "fonts/Apercu-Bold.otf");
    }


    if (view.getTypeface() == Typeface.DEFAULT_BOLD) {
        view.setTypeface(apercuBold, Typeface.BOLD);
    } else if (((TextView) view).getTypeface() == Typeface.DEFAULT) {
        view.setTypeface(apercu);
    }

}

我的意圖是將所有在xml中設置為粗體的TextViews:

<TextView
    android:id="@+id/name_textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold" />

但是,當我稍后在代碼中運行時:

TextView name = (TextView) findViewById(R.id.name_textview);
Fonthelper.setApercuOnTextView(name, getActivity());

它不會輸入我嘗試獲取所有粗體字體的if語句...我也嘗試過使用Typeface.BOLD,但是無論如何它都不會進入該if語句。

目前,我的自定義解決方案是這樣的:

TextView name = (TextView) findViewById(R.id.name_textview);
name.setTypeface(null,Typeface.BOLD);
Fonthelper.setApercuOnTextView(name, getActivity());

有人對此有任何線索嗎?

如何操作:確保您確定view.getTypeface()不為null ...當我超過android:textStyle="bold"找不到Typeface

if (view.getTypeface() == null) {
    Log.e(this.class.getName(), "No textStyle defined in xml");
    // handle?
}
if (view.getTypeface().isBold()) {
    view.setTypeface(apercuBold, Typeface.BOLD);
} else if (((TextView) view).getTypeface() == Typeface.DEFAULT) {
    view.setTypeface(apercu);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM