繁体   English   中英

自定义图标字体不起作用

[英]Custom icons font not working

我正在使用包含两个字体文件(即图标字体文件)的字体家族“ 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");

但是一些用户从市场上下载了一些自定义字体并使用了它。 然后该应用仅显示图标的键(仅显示在“ u”上方),而不显示图标本身。

我猜该字体被系统新安装的字体覆盖,但是如何解决呢?

有人知道如何解决吗?

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

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

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

tx.setTypeface(custom_font);

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

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

我的字体在“资产”文件夹内的“字体”文件夹中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM