【问题标题】:Setting TextView to bold font with xml-attribute and custom font (not working)使用 xml 属性和自定义字体将 TextView 设置为粗体(不起作用)
【发布时间】:2015-10-17 18:13:11
【问题描述】:

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

这是该实用程序中的一种方法的外观(我也有在 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());

有人知道吗?

【问题讨论】:

    标签: java android xml android-layout


    【解决方案1】:

    怎么样: 确保您确定 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);
    }
    

    【讨论】:

    • 嗯.. 非常真实!那么我如何才能知道我是否在 xml 中将 TextView 设置为粗体?
    • 我已经更新了答案,在处理getTypeface 结果之前检查null。我假设你不是在 xml 中谈论,对吧?既然这是你的问题......
    • 顺便说一句,注意这个tmpTypeface == null &amp;&amp; tmpTypefaceBold == null,请改成tmpTypeface == null || tmpTypefaceBold == null...否则你可能会得到一个NullPointerException,如果只有一个null
    • 不错!谢谢!那么我可能必须在代码中设置字体才能正常工作!
    • 你至少要知道可能的空值,但你可以在xml中设置它......没问题
    猜你喜欢
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 2023-03-11
    • 2012-11-27
    相关资源
    最近更新 更多