是否有可能有一个TextView内多个样式?多个、有可能、样式、有一个

2023-09-11 10:26:44 作者:难拥有

是否可以设置多个风格不同的作品文本的一个TextView?

里面

例如,我设置的文字如下:

  tv.setText(第1行+\ N+第2行+\ N+字1 +\ t+ WORD2 +\ t+ WORD3);
 

是否有可能有不同的风格为每个文本元素?例如,一号线加粗,斜体字1,等等。

开发人员指南的常见任务和如何做他们的机器人包含的选择,文本的高亮,或造型部分:

  //获取我们的EditText对象。
VW的EditText =(EditText上)findViewById(R.id.text);

//设置的EditText的文本。
vw.setText(斜体,突出,大胆。);

//如果这只是一个TextView,我们可以这样做:
// vw.setText(斜体,突出,大胆,TextView.BufferType.SPANNABLE);
//迫使它使用Spannable存储中,这样的款式可以连接。
//或者我们可以指定在XML。

//获取的EditText内部文本存储
Spannable海峡= vw.getText();

//创建我们的跨距部,并指定的格式,每个。
str.setSpan(新StyleSpan(android.graphics.Typeface.ITALIC),0,7,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(新BackgroundColorSpan(0xFFFFFF00),8,19,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(新StyleSpan(android.graphics.Typeface.BOLD),21,str.length() -  1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 

但使用明确的位置编号的文本中。有没有干净的方式来做到这一点?

解决方案 Android 在TextView中设置多个样式多个点击事件

在情况下,你想知道如何做到这一点,这里有一个方法:(!感谢再次标记)

  MBOX =新的TextView(上下文);
mBox.setText(Html.fromHtml(< B>中+标题+< / B>中+< BR />中+
            <小>中+说明书+< /小>中+< BR />中+
            <小>中+ DateAdded +< /小>));
 

有关的标签此方法支持的一个非官方列表,请参阅的这个链接。

Is it possible to set multiple styles for different pieces of text inside a TextView?

For instance, I am setting the text as follows:

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

Is it possible to have a different style for each text element? E.g., line1 bold, word1 italic, etc.

The developer guide's Common Tasks and How to Do Them in Android includes 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 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);

But that uses explicit position numbers inside the text. Is there a cleaner way to do this?

解决方案

In case, anyone is wondering how to do this, here's one way: (Thanks to Mark again!)

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

For an unofficial list of tags supported by this method, refer to this link.