12

我需要我textview有不同颜色的文字。我也需要从代码中做到这一点xml,而不是从 java 代码中。有没有人知道这样做的方法?谢谢

例如,我有句子“这是红色的”。我需要单词是绿色的,而红色的单词红色的。

4

4 回答 4

15

有三种方法可以更改 textview 中某些文本的颜色。

  1. 通过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));

  2. 通过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));

  3. 通过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);

如果还有其他方法可以做到这一点,那么我不知道它们。希望这可以帮助

于 2013-10-18T10:42:03.487 回答
15

将您的文本引用到 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>

希望能帮到你

于 2013-07-09T22:54:55.177 回答
0

在 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));
于 2014-05-01T14:06:08.177 回答
-5
<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

于 2013-07-09T22:15:00.203 回答