如何通过遍历字符串并分配不同的颜色,某些关键字在Android的显示文本?遍历、字符串、文本、分配

由网友(愚人码头。)分享简介:我想改变某些关键字的字体颜色。我正在努力实现类似于在某些关键字以不同颜色显示编程环境的文本编辑器。I want to change the font color of certain keywords. What I'm trying to achieve is similar to the text editors...

我想改变某些关键字的字体颜色。我正在努力实现类似于在某些关键字以不同颜色显示编程环境的文本编辑器。

I want to change the font color of certain keywords. What I'm trying to achieve is similar to the text editors of programming environments where certain keywords are displayed in different colors.

例如printf的红色,scanf的绿色,深蓝色等括号内。

For example "printf" in red,"scanf" in green,brackets in dark blue etc.

请注意,我会接受字符串从意图额外的。即,它不是一个固定句子......字符串可能包含任何数量的单词中的任何组合。

Please note that I'll be receiving the string as an extra from intent. i.e,It is not a fixed sentence......the string could contain any number of words in any combination.

所有我想要做的是改变某些词的字体颜色

All I want to do is change the font color of certain words

推荐答案

我得到了我一直在寻找的答案:

I got the answer I was looking for:

public class MainActivity extends Activity {
TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);
        String x="Hello My Name is Umang Mathur";
        tv.setText(x);
        String [] keywordspurple={"Umang","Mathur","Hello"};
        for(String y:keywordspurple)
        {
        fontcolor(y,0xFF8B008B);
        }
        String [] keywordsgreen={"Name","is"};
        for(String y:keywordsgreen)
        {
        fontcolor(y,0xffff0000);
        }
    }

 private void fontcolor(String text,int color) {
            TextView prose=(TextView)findViewById(R.id.textView1);
            Spannable raw=new SpannableString(prose.getText());
            int index=TextUtils.indexOf(raw, text);
            while (index >= 0) {
              raw.setSpan(new ForegroundColorSpan(color), index, index
                  + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
              index=TextUtils.indexOf(raw, text, index + text.length());
            }
            prose.setText(raw);
          }

这code导致绿字设置在puple,2 3个字我留下,因为它是黑色的。

This code resulted in setting 3 words in puple,2 in green and the word "My" was left as it is in black.

阅读全文

相关推荐

最新文章