如何改变文字颜色在句子中的Android中间 [英] how to change text color in the middle of the sentence in android
本文介绍了如何改变文字颜色在句子中的Android中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要更改随机出现在一个句子中字符串的颜色。
I need to change the color of the String which appears randomly in a sentence.
例如:以下这些句子是什么,我需要显示
Ex: These following sentences are what I need to display.
-
上的 #xyz 你怎么样。
我正在学习 #abc 机器人。
在此我必须要改变的话颜色 #xyz , #abc ,即,这与性格开头的#。
In this I have to change the color of the words "#xyz", "#abc" i.e, which starts with the character "#".
我用一些字符串函数分裂(),子串()。但我没有得到我所需要的。
I used some string functions split(), subString(). but I am not getting what i need.
所以,请指导我如何解决这个问题。
so, please guide me how to solve this.
推荐答案
使用SpannableString为前:
Use SpannableString for ex:
SpannableString ss = new SpannableString("hai #xyz how are you.");
ss.setSpan(new ForegroundColorSpan(Color.RED), 4, 9, 0);
试试下面的方法修改每个单词的颜色#:
Try following to change color of each word with #:
String s="hai #xyz how are you.";
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
SpannableString ss = new SpannableString(s);
String[] ss = s.split(" ");
int currIndex = 0;
for (String word : ss) {
if (word.startsWith("#")) {
ss.setSpan(span, currIndex,currIndex+ word.length(), 0);
}
currIndex += (word.length() + 1);
}
这篇关于如何改变文字颜色在句子中的Android中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文