Using SpannableString[/Builder] and Rich-text

﹥>﹥吖頭↗ 提交于 2019-12-02 15:41:00

问题


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


来源:https://stackoverflow.com/questions/8191414/using-spannablestring-builder-and-rich-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!