首页 > 开发 > Android > 正文

如何在一个TextView中实现多种文本风格?

2017-09-08 15:24:03  来源:网友分享

可以为TextView中不同部分的文本设置多种风格(style)吗?
例如,我按照下述方式设置文本:

tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);

每个文本元素都能匹配不同的风格效果吗?例如,第一行,加粗,第一个字,斜体等等。在开发者指南Common Tasks and How to Do Them in Android中包括Selecting, Highlighting, or Styling Portions of Text的方法:

// Get our EditText object.EditText vw = (EditText)findViewById(R.id.text);// Set the EditText's text.vw.setText("Italic, highlighted, bold.");// If this were just a TextView, we could do:// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);// to force it to use Spannable storage so styles can be attached.// Or we could specify that in the XML.// Get the EditText's internal text storageSpannable str = vw.getText();// Create our span sections, and assign a format to each.str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

但这种方法在文本中的使用次数受限,所以,有什么方法可以达到我想要的效果吗?

原问题:Is it possible to have multiple styles inside a TextView?

解决方案

答:Legend
(最佳答案)
遇到这种情况,我的解决办法是编写如下代码:

mBox = new TextView(context);mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" +             "<small>" + description + "</small>" + "<br />" +             "<small>" + DateAdded + "</small>"));

答:CommonsWare
可以试着用Html.fromHtml(),为文本添加粗体和斜体的HTML标签(例如Html.fromHtml("This mixes bold and italic stuff);)。


答:Kent Andersen
如果你习惯上用html,可以创建一个.xml风格:

Textview tv = (TextView)findViewById(R.id.textview);SpannableString text = new SpannableString(myString);text.setSpan(new TextAppearanceSpan(getContext(), R.style.myStyle),0,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);text.setSpan(new TextAppearanceSpan(getContext(), R.style.myNextStyle),6,10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);tv.setText(text, TextView.BufferType.SPANNABLE);