Single TextView with multiple colored text
正如标题所说,我想知道是否可以在单个文本视图元素中实现两个不同的彩色字符。
是的,如果你用html
的font-color
属性格式化String
,然后将它传递给方法Html.fromHtml(your text here)
String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));
您可以打印不带HTML的多种颜色的线条,如下所示:
TextView textView = (TextView) findViewById(R.id.mytextview01);
Spannable word = new SpannableString("Your message");
word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(word);
Spannable wordTwo = new SpannableString("Your new message");
wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(wordTwo);
You can use Spannable
to apply effects to your TextView
:
Here is my example for colouring just the first part of a TextView
text (while allowing you to set the color dynamically rather than hard coding it into a String as with the HTML example!)
mTextView.setText("Red text is here", BufferType.SPANNABLE);
Spannable span = (Spannable) mTextView.getText();
span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
In this example you can replace 0xFFFF0000 with a getResources().getColor(R.color.red)
上一篇: 链接textView并使文本可选
下一篇: 具有多个彩色文本的单个TextView