自定义图标字体不起作用

时间:2018-06-15 07:26:18

标签: android fonts

我正在使用字体系列" font_puck"其中包含两个字体文件(图标字体文件):

<font
    android:font="@font/font_regular"
    android:fontStyle="normal"
    android:fontWeight="400"
    app:font="@font/font_regular"
    app:fontStyle="normal"
    app:fontWeight="400"/>

<font
    android:font="@font/font_light"
    android:fontStyle="normal"
    android:fontWeight="300"
    app:font="@font/font_light"
    app:fontStyle="normal"
    app:fontWeight="300"/>

下面是使用上面fontFamily的TextView:

<TextView
    android:id="@+id/option_item_icon"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="18dp"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="@style/option_list_item_icon"
    android:gravity="start|center_vertical"
    android:fontFamily="@font/font_puck"/>

它用于TextView显示图标。我只需要调用setText(String iconKey)。这适用于系统字体 最后我创建了TextView并设置了文本(文本应该是图标字体的id):

TextView tvIcon = findViewById(R.id.tvicon);
tvIcon.setText("u");

但有些用户从市场上下载了一些自定义字体并使用它。然后应用程序只显示图标的键(仅显示在上面&#34; u&#34;)而不是图标本身。

我猜这个字体会被系统新安装的字体覆盖。但是如何解决呢?

任何人都知道如何解决它?

2 个答案:

答案 0 :(得分:0)

我认为最好的解决方案是在项目中添加字体文件,并将其手动设置为TextView,如:

TextView tx = (TextView)findViewById(R.id.textview1);

Typeface custom_font = Typeface.createFromAsset(getAssets(),  "fonts/abc.ttf");

tx.setTypeface(custom_font);

之后,您的字体不应该被用户字体替换。

答案 1 :(得分:0)

我的CustomTextView:

public class TextViewCustom extends android.support.v7.widget.AppCompatTextView {

public TextViewCustom(Context context) {
    super(context);
}

public TextViewCustom(Context context, AttributeSet attrs) {
    super(context, attrs);
    setCustomAttributes(context, attrs);
}


private void setCustomAttributes(Context ctx, AttributeSet attrs) {
    TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewCustom);
    String customFont = a.getString(R.styleable.TextViewCustom_customFont);

    setCustomFont(ctx, customFont);
    a.recycle();
}

public boolean setCustomFont(Context ctx, String asset) {
    Typeface tf = null;
    try {
        tf = Typefaces.get(ctx, asset);
    } catch (Exception e) {
        Log.e("CustomTextiew", "Could not get typeface: "+e.getMessage());
        return false;
    }

    setTypeface(tf);
    return true;
}

}

将其添加到values文件夹中的attr.xml:

<declare-styleable name="TextViewCustom">
    <attr name="customFont" format="string" />
</declare-styleable>

并在你的xml中使用它:

<ch.atipik.ui.TextViewCustom
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Test"
    android:textColor="#FFFFFF"
    android:textSize="17sp"
    app:customFont="fonts/myfont.ttf" />

我的字体位于“assets”文件夹中的“fonts”文件夹中。

相关问题