Using SpannableString[/Builder] and Rich-text

2019-03-02 16:33发布

问题:

I'm attempting to construct rich-text where the first part says "Looking for: " and is bolded, but the rest is NOT bolded. This is my code:

SpannableStringBuilder lookingForString = new SpannableStringBuilder("Looking for: ");
lookingForString.setSpan(new StyleSpan(Typeface.BOLD), 0, lookingForString.length(),
                                         0);
int start = (lookingForString.length() - 1);
for (int i = 0; i < looking_for_names.length(); ++i) {
// No comma before the first and after the last 'Looking for' value
    if (i > 0) {
        lookingForString.append(", ");
        lookingForString.setSpan(new StyleSpan(Typeface.NORMAL), start,
                                (lookingForString.length() - 1), 0);
        start += 2;
    }

    String lfItem = looking_for_names.optString(i);
    lookingForString.append(lfItem);
    lookingForString.setSpan(new StyleSpan(Typeface.NORMAL), start,
                            (lookingForString.length() - 1), 0);
    start += lfItem.length();
}
tvLookingFor.setText(lookingForString, BufferType.SPANNABLE);

However, the result is that the entire line is bolded. I've tried many variations, but I cannot manage to properly control the typefaces... it tends to retain the first typeface no matter how I code it.

How do I get only "Looking for: " to be bold, but the rest of the text to be regular (non-bolded)?

回答1:

If you just need to Bold the part of text, then just use html tags.

String htmlString="<b>Looking for: Bold</b> and Normal";
tvLookingFor.setText(Html.fromHtml(htmlString), TextView.BufferType.SPANNABLE);