很可能您已经阅读了SpannableStringBuilder
,它允许您为TextView内容中的文本添加颜色。看看下面的代码:
SpannableStringBuilder ssb = new SpannableStringBuilder(<your text>);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ssb.setSpan(fcs, 0, ssb.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ssb);
上面的代码将在大多数情况下工作,但是你想要的是有一个TextView的不同交错的颜色。然后,你应该做到以下几点:
String text = your_text + text_from_database;
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ForegroundColorSpan fcs2 = new ForegroundColorSpan(Color.rgb(0, 255 0));
ssb.setSpan(fcs, 0, your_text, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(fcs2, your_text.length(), ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ssb);
上面的代码将现在的工作,但你会发现,如果添加另一个文本your_another_text
,并希望使用以前fcs
实例第二次,此前有色your_text
现在将失去其格式(颜色)。这次您需要创建另一个ForegroundColorSpan fcs3来格式化SpannableStringBuilder的第三部分。这里的关键是只在setSpan
方法中使用字符样式一次。如下所示:
String testTest = "abcdefgh";
String testTest2 = "ijklmnop";
String testTest3 = "qrstuvwxyz";
SpannableStringBuilder ssb = new SpannableStringBuilder(testTest+testTest2+testTest3);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ForegroundColorSpan fcs2 = new ForegroundColorSpan(Color.rgb(0, 255, 0));
ForegroundColorSpan fcs3 = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ssb.setSpan(fcs, 0, testTest.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
ssb.setSpan(fcs2, testTest.length(), (testTest+testTest2).length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
ssb.setSpan(fcs3, (testTest+testTest2).length(), ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
test.setText(ssb);
如果您知道SpannableStringBuilder中有固定数量的String元素,则此方法很好。如果你希望有一个动态长度和元素数量的TextView,你需要用不同的方法做到这一点。对我有用的是将每个字符串元素转换为SpannableString,使用setSpan
和append
它到TextView。如果您使用循环来构建TextView,这非常有用。
TextView test = (TextView)findViewById(R.id.test);
String testTest = "abcdefgh";
String testTest2 = "ijklmnop";
String testTest3 = "qrstuvwxyz";
SpannableString ssb = new SpannableString(testTest);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ForegroundColorSpan fcs2 = new ForegroundColorSpan(Color.rgb(0, 255, 0));
ForegroundColorSpan fcs3 = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ssb.setSpan(fcs, 0, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
test.setText(ssb);
SpannableString ssb2 = new SpannableString(testTest2);
ssb2.setSpan(fcs2, 0, ssb2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
test.append(ssb2);
SpannableString ssb3 = new SpannableString(testTest3);
ssb3.setSpan(fcs3, 0, ssb3.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
test.append(ssb3);
阅读相关SO线程 - http://stackoverflow.com/questions/4283755/android-question-implementing-a-rich-text-editor – adatapost 2012-01-02 02:45:29