【问题标题】:2 different colors for Text in same text view in android [duplicate]android中相同文本视图中文本的2种不同颜色[重复]
【发布时间】:2013-02-13 05:39:56
【问题描述】:

我有一个TextView小部件,如下图

<TextView 
        android:text="@string/inputText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

inputText 在 Strings.xml 中定义为

<String name="inputText">The value of input is positive now</String>

现在,我希望整个文本以棕色显示,并且只有“正面”以绿色显示。

有什么办法吗? 简而言之,我的问题是同时为同一个文本视图进行多种着色

【问题讨论】:

标签: android textview textcolor


【解决方案1】:

这是这个问题Change text color of one word in a TextView的重复。

String first = "This word is ";
String next = "<font color='#EE0000'>red</font>";
t.setText(Html.fromHtml(first + next));

【讨论】:

  • 哦,没看到另一个,反正谢谢。
  • 然后标记为已回答;)
  • 这不再起作用(在 4.2.2 设备上测试)
  • 这应该被标记为接受的答案
  • 这里有一个更新:颜色值不应包含 Alpha 通道!
【解决方案2】:

您可以在strings.xml 中使用CDATA 以某种HTML 格式存储您的字符串,并使用Html.fromHTML 将其显示在您的TextView 中。

字符串.xml

<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));

【讨论】:

  • 非常感谢您的解答!
【解决方案3】:

使用这种方法:用 html 格式化字符串

String text = "<font color=#cc0029>Text with Color first</font> <font color=#ffcc00>Text with Color second</font>";
yourtextview.setText(Html.fromHtml(text));

【讨论】:

    【解决方案4】:

    使用 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);
    

    【讨论】:

      【解决方案5】:

      试试这个,

      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);
      

      【讨论】:

        猜你喜欢
        • 2012-03-06
        • 2015-06-14
        • 1970-01-01
        • 2015-06-01
        • 1970-01-01
        • 2013-07-07
        • 2013-10-19
        • 1970-01-01
        • 2019-11-25
        相关资源
        最近更新 更多