xml 代码中具有不同颜色文本的文本视图 [英] Text view with different colored texts in xml code
问题描述
我需要我的 textview
有不同颜色的文本.我还需要从 xml
代码中执行此操作,而不是从 java 代码中执行此操作.有没有人知道这样做的方法?谢谢
I need my textview
to have different colored texts. Also I need to do this from xml
code, non from java code. Is there anyone who knows some way for doing this?
Thanks
例如我有一句话这是红色的".我需要单词是绿色的,而单词red是红色的.
e.g. I have sentence "This is red". I need words to be green, and word red to be red.
推荐答案
有三种方法可以改变 textview 中某些文本的颜色.
There are three ways to change the color of some text inside a textview.
通过
strings.xml
文件在 (res>values) 中,使用标签 (<![CDATA[<p>This is green <font color='红色的十六进制值'>这是红色的</font>.</p>]]>
) 然后在java代码中将textview声明为myTextView.setText(Html.fromHtml(getString(R.string.myText));
through
strings.xml
file in (res>values), using the tag (<![CDATA[<p>This is green <font color='hexvalue of red'>and this is red</font>.</p> ]]>
) and then declaring the textview in java code asmyTextView.setText(Html.fromHtml(getString(R.string.myText));
通过java代码,使用HTML标签String text = "<font color='hexvalue of green'>这是绿色</font><font color='hexvalue of red'>这是红色的</font>.";myTextView.setText(Html.fromHtml((text));
through java code, using the HTML tag String text = "<font color='hexvalue of green'>This is green</font> <font color='hexvalue of red'>and this is red</font>."; myTextView.setText(Html.fromHtml((text));
通过Spannable
文本使用java代码.
through Spannable
text using java code.
Spannable span
= new SpannableString("My String");
span.setSpan(new ForegroundColorSpan(Color.RED), start_position,
end_position,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(span);
如果还有其他方法可以做到这一点,那么我不知道它们.希望这会有所帮助
If there are other ways to do it then I'm not aware of them. Hope this helps
这篇关于xml 代码中具有不同颜色文本的文本视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!