在XML中定义的不同颜色的TextView不同颜色、定义、XML、TextView

2023-09-07 16:13:23 作者:寂寞梧桐锁深秋

我想定义不同颜色单一的TextView象下面这样:

 <字体颜色=黄色>喜< / FONT><字体颜色=红色>人人< / FONT>
 

我看到此链接:Is有可能有一个TextView里面的多种样式?。但它并不适合我。我想知道我可以通过XML定义它。是否有可能这样做吗? 谢谢

解决方案

我们不能设置在XML文件中,但我们可以设置为编码... 您必须使用文本spannable .. 这里是例子。

  

字符串文本=嗨@@你好@@;

     

TextView.setText(setSpanBetweenTokens(文字,@@,新   ForegroundColorSpan(Color.RED)));

您setSpanBetweenTokens方法

  

 公共静态的CharSequence setSpanBetweenTokens(CharSequence的文字,
            字符串标记,CharacterStyle ... CS)
        {
            //开始和结束参照点,其中的跨度将适用
            INT tokenLen = token.length();
            INT开始= text.toString()的indexOf(标记)+ tokenLen。
            INT端= text.toString()的indexOf(令牌,开始)。


如果(开始> -1放大器;&安培;末> -1)
 
android中colors.xml颜色设置资源文件

  {
          SpannableStringBuilder SSB =新SpannableStringBuilder(文本);
          对于(CharacterStyle C:CS)
              ssb.setSpan(C,开始,结束,0);

          之前和之后跨度//删除令牌
          ssb.delete(结束,结束+ tokenLen);
          ssb.delete(开始 -  tokenLen,启动);

          文= SSB;
      }
      返回文本;
  }
 

I want to define different colors in single TextView like below:

<font color="yellow">Hi </font><font color="red">everybody</font>  

I saw this link: Is it possible to have multiple styles inside a TextView?. But it doesn't suit me. I would like to know how can I define it via XML. Is it possible to do this? Thanks

解决方案

we can't set in XML file but we can set as coding... You have to use text spannable.. here is example..

String text = "Hi @@hello@@";

TextView.setText(setSpanBetweenTokens(text, "@@", new ForegroundColorSpan(Color.RED)));

your setSpanBetweenTokens Method

public static CharSequence setSpanBetweenTokens(CharSequence text,
            String token, CharacterStyle... cs)
        {
            // Start and end refer to the points where the span will apply
            int tokenLen = token.length();
            int start = text.toString().indexOf(token) + tokenLen;
            int end = text.toString().indexOf(token, start);


if (start > -1 && end > -1)

      {               
          SpannableStringBuilder ssb = new SpannableStringBuilder(text);
          for (CharacterStyle c : cs)
              ssb.setSpan(c, start, end, 0);

          // Delete the tokens before and after the span
          ssb.delete(end, end + tokenLen);
          ssb.delete(start - tokenLen, start);

          text = ssb;
      }
      return text;
  }