在安卓中,同一文本视图中的文本可以设置为两种不同的颜色。

6
我有一个TextView小部件,如下所示。
<TextView 
        android:text="@string/inputText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

输入文本在Strings.xml中定义为:
<String name="inputText">The value of input is positive now</String>

现在,我希望整段文字以棕色显示,只有“positive”一词以绿色显示。是否有办法实现这个效果?简而言之,我的问题是如何在同一文本视图中同时使用多种颜色。

你尝试过http://developer.android.com/reference/android/text/Spannable.html或者https://dev59.com/22015IYBdhLWcg3w_Qw_?rq=1吗? - sandrstar
5个回答

15

哦,没看到另一个,不管怎样谢谢你。 - user2115214
then mark as answered ;) - M4tchB0X3r
这个不再起作用了(在4.2.2设备上测试过)。 - Marcel Falliere
这是已接受的答案。 - chip
这里是更新: 颜色值不应包含 Alpha 通道! - Tobliug

7
你可以在strings.xml中使用CDATA来存储带有HTML格式的字符串,并使用Html.fromHTML来在TextView中显示它。
<string name="inputText">
    <![CDATA[
      <p>The value of input is <font color='#00ff00'>positive</font> now.</p>
    ]]>
</string>

Java 代码

myTextView.setText(Html.fromHtml(getString(R.string.inputText));

2
请使用以下方法:使用html格式化字符串。
String text = "<font color=#cc0029>Text with Color first</font> <font color=#ffcc00>Text with Color second</font>";
yourtextview.setText(Html.fromHtml(text));

1
使用Spannable来实现:
String text = "<font color='brown'>The value of input is </font><font color='green'> positive </font><font color='brown'> color </font>";
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);

0

试试这个,

TextView tv = (TextView)findViewById(R.id.mytextview01);

SpannableString WordtoSpan = tv.getText();

WordtoSpan.setSpan(new ForegroundColorSpan(Color.GREEN), 23, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tv.setText(WordtoSpan);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接