2016-01-27 43 views
0

我做了一個自定義的TextView加載字體(在我的情況下它是IcoMoon字體)。我的自定義的TextView類看起來如下:自定義字體在Android的運行時不工作

public class CustomTextView extends TextView { 

    public CustomTextView(Context context) { 
     super(context); 
     init(context); 
    } 

    public CustomTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(context); 
    } 

    public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     init(context); 
    } 

    @SuppressWarnings("NewApi") 
    public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 
     init(context); 
    } 

    /** 
    * Load and apply font for this widget 
    * 
    * @param context to initialize 
    */ 
    private void init(Context context) { 
     Typeface font = Typeface.createFromAsset(context.getAssets(), "icomoon.ttf"); 
     if(font != null) 
      setTypeface(font); 
    } 
} 

在我的佈局文件,我用這個類,如下:

<com.test.CustomTextView 
    android:id="@+id/txt_about_hotel_icon" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="&#xe020;" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:textColor="@color/textColorPrimary" /> 

一切順利的話,當我使用這個類的佈局和設置文本顯示字體圖標。現在的問題開始時我嘗試使用這個類在我的活動類設置爲下面的字體圖標:

CustomTextView txtHotelIcon = (CustomTextView) findViewById(R.id.txt_about_hotel_icon); 
txtHotelIcon.setText("&#xe020;"); 

現在的問題是,如果我設置在XML佈局的字體字符,它的偉大工程和字體圖標可見。但是,當我嘗試在運行時設置此字體文本值時,它顯示確切的文本而不是顯示字體圖標。

請建議我如何解決這個問題。

回答

0

使用另一種格式據我知道TextView不直接支持的HTML標記,所以你可以嘗試以下操作之一:

  • 負載您的文字使用setText(Html.fromHtml("&#xe020;"))
  • 用Unicode代替HTML表示法setText("\uE020")

還沒有嘗試過那些圖標字體,所以他們可能無法正常工作。

+0

感謝您的解決方案。 Html.fromHtml適合我。 :) –

0

你應該在代碼

CustomTextView txtHotelIcon = (CustomTextView) findViewById(R.id.txt_about_hotel_icon); 
txtHotelIcon.setText("\ue020");