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



本文选自StackOverflow(简称:SOF)精选问答汇总系列文章之一,本系列文章将为读者分享国外最优质的精彩问与答,供读者学习和了解国外最新技术,本文为大家讲解Android中,如何在一个TextView中实现多种文本风格。


问:blahdiblah

可以为TextView中不同部分的文本设置多种风格(style)吗?

例如,我按照下述方式设置文本:

1
tv.setText(line1 + " " + line2 + " " + word1 + " " + word2 + " " + word3);

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 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 storage
Spannable 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);

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

答:Legend

(最佳答案)

遇到这种情况,我的解决办法是编写如下代码:

1
2
3
4
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 <b>bold</b> and <i>italic</i> stuff);)。

答:Kent Andersen

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

1
2
3
4
5
6
7
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);

原文链接:http://stackoverflow.com/questions/1529068/is-it-possible-to-have-multiple-styles-inside-a-textview

文章选自StackOverFlow社区,鉴于其内容对于开发者有所帮助,现将文章翻译于此,供大家参考及学习。9Tech将每日持续更新,读者可点击StackOverflow(简称:SOF)精选问答汇总,查看全部译文内容。同时,我们也招募志同道合的技术朋友共同翻译,造福大家!报名请发邮件至zhangqi_wj@cyou-inc.com。


原文地址:https://www.cnblogs.com/aikongmeng/p/3697349.html