【问题标题】:How can I set a word as bold in a TextView with fontFamily open sans semi bold in Android?如何在 Android 中使用 fontFamily 打开无半粗体的 TextView 将单词设置为粗体?
【发布时间】:2020-05-08 00:57:03
【问题描述】:

我需要帮助来理解以下问题。

我需要将 TextView 的单个单词设置为粗体。

我有一个带有 ID 为 myTextView 的 TextView 的布局:

  <TextView
      android:id="@+id/myTextView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:fontFamily="@font/open_sans_semi_bold"
      android:textColor="#d94256"
      android:textSize="20sp" />

我以这种方式以编程方式将文本设置到此视图:

myTextView.text = HtmlCompat.fromHtml("My fancy string where I want to show this <b>word</b> bold", HtmlCompat.FROM_HTML_MODE_LEGACY)

另外,我尝试使用可跨字符串生成器,但在这两种情况下我都得到了the result of this image

为什么我没有得到类似this 的东西?当我改变这一行时,我得到了这个结果:

android:fontFamily="@font/open_sans_semi_bold"

对于这个:

android:fontFamily="@font/open_sans_regular"

而且,如果我设置了

android:fontFamily="@font/open_sans_bold"

我可以看到this result

我在 google git 存储库中找到了 open_sans_semi_boldopen_sans_boldopen_sans_regular 的 ttf 文件。

Html &lt;b&gt; 标签不应该和 OpenSans Bold 一样粗吗?

【问题讨论】:

    标签: android html textview font-family


    【解决方案1】:

    这是我的字符串高亮功能。将子字符串显示为粗体,此外,您可以根据需要为突出显示的字符串定义不同的颜色。

    @Nullable
    public static Spannable highlightString(@NonNull String s, @NonNull String subString, int color) {
    
        int startPos = s.toLowerCase(Locale.getDefault()).indexOf(subString.toLowerCase(Locale.getDefault()));
        int endPos = startPos + subString.length();
    
        if (startPos != -1) {
            Spannable spannable = new SpannableString(s);
            ColorStateList colorStateList = new ColorStateList(new int[][]{new int[]{}}, new int[]{color});
            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, colorStateList, null);
            try {
                spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
    
            return spannable;
        }
        else
            return null;
    }
    

    用法:

    Spannable highlightedText = highlightString("My fancy string where I want to show this word bold", "word", Color.BLUE);
    if (highlightedText != null)
        myTextView.setText(highlightedText);
    

    【讨论】:

    • 感谢您的回复!只要 TextView fontFamily 比 openSans 半粗体“不那么粗体”,我就尝试了你的代码并且工作正常。这与发生在我身上的问题相同。再次感谢您的帮助!
    • @SergiLlamas 你在你的 xml 中尝试过 android:textStyle 吗?我也推荐fonts.google.com
    • 感谢您的回复,但我认为这行不通,因为我只需要将字符串中的一个单词设置为粗体,而不是完整的字符串。但是可以使用 xml 设置 textStyle semibold 吗?我的意思是,不使用 fontFamily
    • 如果不使用fontFamily,将使用默认字体
    • 不适用于我使用的自定义字体(avenir medium)
    猜你喜欢
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2023-03-29
    • 2014-04-29
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多