【问题标题】:Custom font not working at runtime in Android自定义字体在 Android 运行时不起作用
【发布时间】:2016-01-27 15:53:59
【问题描述】:

我制作了一个自定义 TextView 来加载字体(在我的例子中是 IcoMoon 字体)。我的自定义 TextView 类如下所示:

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" />

当我在布局中使用这个类并将文本设置为显示字体图标时,一切都很顺利。现在,当我尝试在我的 Activity 类中使​​用这个类来设置字体图标时,问题就开始了:

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

现在的问题是,如果我在 XML 布局中设置字体字符,效果很好并且字体图标可见。但是当我尝试在运行时设置此字体文本值时,它会显示确切的文本而不是显示字体图标。

请建议我如何解决此问题。

【问题讨论】:

    标签: android customization textview custom-font


    【解决方案1】:

    据我所知,TextView 不直接支持 HTML 表示法,因此您可以尝试以下方法之一:

    • 使用setText(Html.fromHtml("&amp;#xe020;")) 加载您的文本
    • 将 HTML 符号替换为 Unicode setText("\uE020")

    还没有尝试过带有图标字体的那些,所以它们可能无法正常工作。

    【讨论】:

    • 感谢您的解决方案。 Html.fromHtml 为我工作。 :)
    【解决方案2】:

    你应该在代码中使用另一种格式

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      相关资源
      最近更新 更多