简体   繁体   中英

How can I set a word as bold in a TextView with fontFamily open sans semi bold in Android?

I need help to understand the following issue.

I need to set a single word of a TextView as bold.

I have a layout with a TextView with id myTextView :

  <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" />

I set text to this view programmatically this way:

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

Also, I tried to use spannable string builder but I got the result of this image in both cases.

Why don't I get something like this ? I get this result when I change this line:

android:fontFamily="@font/open_sans_semi_bold"

for this one:

android:fontFamily="@font/open_sans_regular"

And also, if I set

android:fontFamily="@font/open_sans_bold"

I can see this result

I found the ttf files for open_sans_semi_bold , open_sans_bold and open_sans_regular in a google git repository.

Isn't Html <b> tag supposed to be as bold as OpenSans Bold?

This is my string highlight function. Shows substring bold, in addition you can define different color for highlighted string if you want.

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

Usage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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