【问题标题】:Change text color within a string? [duplicate]更改字符串中的文本颜色? [复制]
【发布时间】:2012-11-21 20:49:37
【问题描述】:

可能重复:
Different colors in TextView defined in XML

这可能是一个非常愚蠢的问题,但我无法弄清楚。 我想要做的是更改字符串中文本的颜色,如下所示: “嗨,”+colorRed“你好吗?”

^ 试图将“你”这个词改成红色。

【问题讨论】:

  • 同意@Pearsonartphoto - 请注意,并非所有视图都支持这一点。

标签: android android-layout


【解决方案1】:

我知道的最简单的方法就是使用 html。

String color = "Hi, how are <font color='#EE0000'>you</font>";
**YOUR_TEXTVIEW**.setText(Html.fromHtml(color));

了解更多Detail Refer This

【讨论】:

    【解决方案2】:
    String s = "Hi, how are <font color='red'>you</font>?";
    textView.setText(Html.fromHtml(s), TextView.BufferType.SPANNABLE);
    

    【讨论】:

      【解决方案3】:

      我认为最好的(而且耗时更少)的方法是 - 使用Spannable。例如:

      final String text = "Hi, how are ";
      final Spannable spanYou = new SpannableString("you");
      spanYou.setSpan(new ForegroundColorSpan(Color.RED), 0, spanYou.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      textView.setText(text);
      textView.append(spanYou);
      

      Html.fromHtml() 首先将您的文本解析为 html,然后使用 Spannable。

      【讨论】:

        猜你喜欢
        • 2014-02-02
        • 2012-06-15
        • 2014-10-12
        • 2012-04-13
        • 2014-07-22
        • 2017-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多