我正在尝试构建富文本,其中第一部分说“寻找:”并且是粗体,但其余部分没有粗体。这是我的代码:
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);
然而,结果是整条线都是粗体。我尝试了很多变化,但我无法正确控制字体...无论我如何编码它都会保留第一个字体。
我如何才能将“寻找:”变为粗体,但其余文本是否定期(非粗体)?
答案 0 :(得分:4)
如果你只需要加粗部分文字,那么只需使用html标签即可。
String htmlString="<b>Looking for: Bold</b> and Normal";
tvLookingFor.setText(Html.fromHtml(htmlString), TextView.BufferType.SPANNABLE);