繁体   English   中英

将TextView设置为带有xml属性和自定义字体的粗体字体(不起作用)

[英]Setting TextView to bold font with xml-attribute and custom font (not working)

我正在构建一个应用程序,我们正在使用一种自定义字体Apercu,您可能听说过。 无论如何,我已经构建了一个实用程序来帮助我在所有元素上设置字体。

这就是该util中的方法之一(我也有在ViewGroup上设置此字体的方法,在其中我遍历所有元素):

public static void setApercuOnTextView(final TextView view, final Context context) {
    Typeface tmpTypeface = apercu;
    Typeface tmpTypefaceBold = apercuBold;

    if (tmpTypeface == null && tmpTypefaceBold == null) {
        apercu = Typeface.createFromAsset(context.getAssets(), "fonts/Apercu.otf");
        apercuBold = Typeface.createFromAsset(context.getAssets(), "fonts/Apercu-Bold.otf");
    }


    if (view.getTypeface() == Typeface.DEFAULT_BOLD) {
        view.setTypeface(apercuBold, Typeface.BOLD);
    } else if (((TextView) view).getTypeface() == Typeface.DEFAULT) {
        view.setTypeface(apercu);
    }

}

我的意图是将所有在xml中设置为粗体的TextViews:

<TextView
    android:id="@+id/name_textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold" />

但是,当我稍后在代码中运行时:

TextView name = (TextView) findViewById(R.id.name_textview);
Fonthelper.setApercuOnTextView(name, getActivity());

它不会输入我尝试获取所有粗体字体的if语句...我也尝试过使用Typeface.BOLD,但是无论如何它都不会进入该if语句。

目前,我的自定义解决方案是这样的:

TextView name = (TextView) findViewById(R.id.name_textview);
name.setTypeface(null,Typeface.BOLD);
Fonthelper.setApercuOnTextView(name, getActivity());

有人对此有任何线索吗?

如何操作:确保您确定view.getTypeface()不为null ...当我超过android:textStyle="bold"找不到Typeface

if (view.getTypeface() == null) {
    Log.e(this.class.getName(), "No textStyle defined in xml");
    // handle?
}
if (view.getTypeface().isBold()) {
    view.setTypeface(apercuBold, Typeface.BOLD);
} else if (((TextView) view).getTypeface() == Typeface.DEFAULT) {
    view.setTypeface(apercu);
}

暂无
暂无

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

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