在TextView中可以有多个样式吗?

在TextView中可以有多个样式吗?

是否可以为TextView中的不同文本设置多个样式?

例如,我将文本设置为:

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

对于每个文本元素是否可能有不同的样式?例如,行1粗体,字1斜体等。

开发商指南常见任务及其在Android中的实现方法包括选择、高亮显示或设计文本的部分:

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

但在文本中使用显式位置号。有更干净的方法吗?



慕的地6264312
浏览 551回答 3
3回答

胡子哥哥

万一有人想知道如何做到这一点,这里有一个方法:(再次感谢Mark!)mBox = new TextView(context);mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" +              "<small>" + description + "</small>" + "<br />" +              "<small>" + DateAdded + "</small>"));

呼啦一阵风

试一试Html.fromHtml(),并用粗体和斜体HTML标记文本,例如:Spanned&nbsp;text&nbsp;=&nbsp;Html.fromHtml("This&nbsp;mixes&nbsp;<b>bold</b>&nbsp;and&nbsp;<i>italic</i>&nbsp;stuff");textView.setText(text);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android