其他分享
首页 > 其他分享> > android-使用SpannableString [/ Builder]和RTF文本

android-使用SpannableString [/ Builder]和RTF文本

作者:互联网

我正在尝试构建富文本格式,其中第一部分显示为“ Looking for:”,并以粗体显示,但其余部分未以粗体显示.这是我的代码:

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

但是,结果是整行都加粗了.我已经尝试了许多变体,但是我无法设法正确控制字体……无论我如何编码,它都倾向于保留第一个字体.

如何仅使“ Looking for:”为粗体,而其余文本为常规(非粗体)?

解决方法:

如果只需要加粗文本部分,则只需使用html标签.

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

标签:android,spannablestring
来源: https://codeday.me/bug/20191013/1910955.html