一个 TextView 中的 Android 多色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10140893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android multi color in one TextView
提问by Hüseyin Zeki
Possible Duplicate:
Is it possible to have multiple styles inside a TextView?
可能的重复:
TextView 中是否可以有多种样式?
I want my TextView to show some part of its text in red and others in black. It's content (the text) is created dynamically and i don't know how many words will be red colored.
我希望我的 TextView 以红色显示其文本的某些部分,以黑色显示其他部分。它的内容(文本)是动态创建的,我不知道有多少单词会是红色的。
Is there any way to do this like in html-css?
有没有办法像在 html-css 中那样做到这一点?
回答by Costi Muraru
You can use Spannable to achieve what you want.
您可以使用 Spannable 来实现您想要的。
String text = "This is <font color='red'>red</font>. This is <font color='blue'>blue</font>.";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
} else {
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
}
回答by Khan
try this way
试试这个方法
TextView tv = (TextView)findViewById(R.id.tv);
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 5, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(wordtoSpan);