正如标题所说,我想知道是否有可能在单个textview元素中实现两个不同颜色的字符。


当前回答

你可以使用Spannable应用效果到你的TextView:

这是我的例子,只是一个TextView文本的第一部分上色(同时允许您动态设置颜色,而不是硬编码成字符串与HTML的例子!)

    mTextView.setText("Red text is here", BufferType.SPANNABLE);
    Spannable span = (Spannable) mTextView.getText();
    span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
             Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

在这个例子中,你可以将0xFFFF0000替换为getResources().getColor(R.color.red)

其他回答

@Swapnil Kotwal回答的Kotlin版本。

Android Studio 4.0.1, Kotlin 1.3.72

val greenText = SpannableString("This is green,")
greenText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someGreenColor), null), 0, greenText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.text = greenText

val yellowText = SpannableString("this is yellow, ")
yellowText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someYellowColor), null), 0, yellowText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(yellowText)

val redText = SpannableString("and this is red.")
redText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someRedColor), null), 0, redText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(redText)

是的,如果你用html的font-color属性格式化字符串,然后把它传递给方法html . fromhtml(你的文本在这里)

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

我已经写下了一些类似于这个问题的其他问题的代码,但这个问题被复制了,所以我不能回答那里,所以我只是把我的代码放在这里,如果有人寻找相同的要求。

它不是完全工作的代码,你需要做一些小的改变让它工作。

代码如下:

我使用@Graeme的想法使用可扩展文本。

String colorfulText = "colorfulText";       
    Spannable span = new SpannableString(colorfulText);             

    for ( int i = 0, len = colorfulText.length(); i < len; i++ ){
        span.setSpan(new ForegroundColorSpan(getRandomColor()), i, i+1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                     
    }   

    ((TextView)findViewById(R.id.txtSplashscreenCopywrite)).setText(span);

随机色法:

  private int getRandomColor(){
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

自从API 24以来,你有FROM_HTML_OPTION_USE_CSS_COLORS,所以你可以在CSS中定义颜色,而不是一直重复使用font color=" 更清楚-当你有一些html,你想突出一些预定义的标签-你只需要在你的html顶部添加CSS片段

Kotlin中的生成器函数:

  val text = buildSpannedString {
      append("My red text")
      setSpan(
          ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.red)),
          3,
          6,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
      )
  }
  textView?.setText(text)