为什么以下代码不起作用?它适用于Toast但不适用于TextView。当我运行程序时,boldName不会显示为粗体,但当我将其设置为Toast时,它确实显示为粗体。有没有人有其他解决方案?
String boldName = "<b>" + name + "</b>";
Spanned conBold = Html.fromHtml(boldName);
chosen_contact.setText("You have chosen " + conBold + " as your contact.");
答案 0 :(得分:20)
老实说,我不确定为什么TextViews按照他们的方式行事,你可以将它设置为粗体,但只有当整个TextView都是粗体时,如果只有部分粗体是粗体的话你就不能这样做那里还有其他的弦乐。
但是,此代码适用于您:
// a SpannableStringBuilder containing text to display
SpannableStringBuilder sb = new SpannableStringBuilder("You have chosen " + name + " as your contact.");
// create a bold StyleSpan to be used on the SpannableStringBuilder
StyleSpan b = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
// set only the name part of the SpannableStringBuilder to be bold --> 16, 16 + name.length()
sb.setSpan(b, 16, 16 + name.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
chosen_contact.setText(sb); // set the TextView to be the SpannableStringBuilder
答案 1 :(得分:0)
您可以使用SpannableStringBuilder,因为它是从spannable和CharSequence实现的,您也可以使用以下内容执行任何操作
TextView txtTest = (TextView) findViewById(R.id.txt);
String text = "This is an example";
final SpannableStringBuilder str = new SpannableStringBuilder(text);
str.setSpan(new TypefaceSpan("monospace"), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new TypefaceSpan("serif"), 9, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.white)), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.grey)), 6, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txtTest.setText(str);
我在values
中添加了colors.xml<color name="black">#000000</color>
<color name="grey">#DCDCDC</color>
<color name="white">#FFFFFF</color>