java - 使用 xml 属性和自定义字体将 TextView 设置为粗体字体(不起作用)

标签 java android xml android-layout

我正在构建一个应用程序,我们正在使用一种名为 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 中设置为粗体的所有 TextView:

<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);
}

关于java - 使用 xml 属性和自定义字体将 TextView 设置为粗体字体(不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655134/

相关文章:

android - 在 bintray 上上传二进制文件时 HTTP/1.1 401 Unauthorized

android - fragment startActivityForResult 在回调 onActivityResult 时总是返回 resultCode 0 和 intent null

java - 使用 Java 从 XML 中提取数据的简单方法

java - 使用 .put 方法 stub (Mockito) 模拟 net.sf.ehcache.Cache (ehcache)

java - 如果服务器上的json数据发生变化,如何更新?

java - 如何才能实现对某个主题的消息只处理一次?

java - 使用连接多个 View 的单个手势检测器获得双击/触摸 View

java - 使用 Camel 将 XML 转为 Json

xml - XML Schema 是 SGML DTD 的子集吗?

java - 如何在浏览器中验证 pdf 查看器