在XML中定义的不同颜色的TextView [英] Different colors in TextView defined in XML

查看:361
本文介绍了在XML中定义的不同颜色的TextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我看到此链接:<一href="http://stackoverflow.com/questions/1529068/is-it-possible-to-have-multiple-styles-inside-a-textview">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(令牌,开始)。


如果(开始&gt; -1放大器;&安培;末&GT; -1)
 

  {
          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;
  }

这篇关于在XML中定义的不同颜色的TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆