2016-01-27 29 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");