android中的自定义TextView具有不同的颜色词 [英] Custom TextView in android with different color words
本文介绍了android中的自定义TextView具有不同的颜色词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以让 textview
为每个单词设置不同的颜色?甚至每一个字母?我尝试扩展 textview
并创建它,但是我想到的问题是,如何同时用不同的颜色绘制所有文本?
Is it possible to have a textview
to have different color for every word? Or even every letter? I tried extending textview
and creating it but however I thought of the problem is, how would I draw all the the text out at the same time with different colors?
推荐答案
final SpannableStringBuilder str = new SpannableStringBuilder(text);
str.setSpan(
new ForegroundColorSpan(Color.BLUE),
wordStart,
wordEnd,
SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
);
myTextView.setText(str);
编辑:让所有Java"变成绿色
EDIT: To make all "Java" green
final Pattern p = Pattern.compile("Java");
final Matcher matcher = p.matcher(text);
final SpannableStringBuilder spannable = new SpannableStringBuilder(text);
final ForegroundColorSpan span = new ForegroundColorSpan(Color.GREEN);
while (matcher.find()) {
spannable.setSpan(
span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
myTextView.setText(spannable);
这篇关于android中的自定义TextView具有不同的颜色词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文