简体   繁体   English

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

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

I'm building an app and we're using a custom font called Apercu, which you might heard of. 我正在构建一个应用程序,我们正在使用一种自定义字体Apercu,您可能听说过。 Anyway, I've built a util to help me set the font on all the elements. 无论如何,我已经构建了一个实用程序来帮助我在所有元素上设置字体。

This is how one of the methods in that util looks like (I also have methods for setting this font on a ViewGroup, where I loop through all elements): 这就是该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);
    }

}

My intention with this was that all TextViews that I set to bold in the xml: 我的意图是将所有在xml中设置为粗体的TextViews:

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

However, when I later in the code run this: 但是,当我稍后在代码中运行时:

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

It does not enter the if-statement where I try to get all bold fonts... I've also tried with Typeface.BOLD, but it does not get into that if-statement anyways. 它不会输入我尝试获取所有粗体字体的if语句...我也尝试过使用Typeface.BOLD,但是无论如何它都不会进入该if语句。

My custom solution at the moment is to do like this: 目前,我的自定义解决方案是这样的:

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

Does anyone have any clue on this? 有人对此有任何线索吗?

How about: Make sure you are certain view.getTypeface() isn't null ... When I outqouted android:textStyle="bold" no Typeface was found. 如何操作:确保您确定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