我需要我textview
有不同颜色的文字。我也需要从代码中做到这一点xml
,而不是从 java 代码中。有没有人知道这样做的方法?谢谢
例如,我有句子“这是红色的”。我需要单词是绿色的,而红色的单词是红色的。
有三种方法可以更改 textview 中某些文本的颜色。
通过strings.xml
文件 in (res>values),使用标记 ( <![CDATA[<p>This is green <font color='hexvalue of red'>and this is red</font>.</p> ]]>
),然后在 java 代码中将 textview 声明为myTextView.setText(Html.fromHtml(getString(R.string.myText));
通过java代码,使用HTML标签 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 代码的文本。
Spannable span
=new SpannableString("My String");
span.setSpan(new ForegroundColorSpan(Color.RED), start_position,
end_position,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(span);
如果还有其他方法可以做到这一点,那么我不知道它们。希望这可以帮助
将您的文本引用到 string.xml 并使用 html 字体标签,通过使用这种方式,您还可以更改每个字母的颜色。
只需在 java 中为该字符串添加它:
TextView tv=(TextView)findViewById(R.id.tv);
tv.setText(Html.fromHtml(getString(R.string.any_text)));
和
在 string.xml 中:
<string name="any_text">
<![CDATA[ <b><font color=#ff0000>write</b> your <b><font color=#0000ff>text</b> here .
]]>
</string>
希望能帮到你
在 Java 类中定义 TextView 如下:
TextView tv = (TextView) findViewById(R.id.text1);
String text = "<font color=#cc0029>write any thing here</font> "+
"<font color=#ffcc00>write any thing here 2</font>";
tv.setText(Html.fromHtml(text));
<TextView
android:id="@+id/yourUniqueTextViewID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:textColor="@color/RED" />
其中“RED”是一个命名常量,您必须在 xml 文件中的 res/values/ 下定义。通常我创建“colors.xml”。
或者查看一组好的预定义颜色:Web colors in an Android color xml resource file