保持SpannableStringBuilder中的跨度

时间:2014-12-31 19:33:00

标签: android

对不起所有人。我以前从未在这里发布过,所以我希望我能做到这一点 我正在尝试使用SpannableStringBuilder。我想将它们分开,添加跨度,并将它们重新组合在一起。我不认为我可以使用HTML,因为我打算使用HTML无法复制的跨度。我很困惑,因为有些操作是为了保留跨距,但据我所知,它们不是。例如s2 = new SpannableStringBuilder(s4);应该复制跨度,但不是。
以下是我需要做的一个例子。从长远来看,我希望最终文本是:
[红色] [红色]是[红色] 测试 [红色]

你能告诉我我做错了什么吗?

// tvHistory is a TextView
// 0         1
// 01234567890123
// This is a Test

final int FLAGS = Spannable.SPAN_EXCLUSIVE_EXCLUSIVE;
final int COLOR = 0xFFff0000;

SpannableStringBuilder s1 = new SpannableStringBuilder("This");
SpannableStringBuilder s2;
SpannableStringBuilder s3;
SpannableStringBuilder s4;

// works - sets "This" to red
s1.setSpan(new ForegroundColorSpan(COLOR), 0, s1.length(), FLAGS);

// works - <red>This<red> is a test
s4 = new SpannableStringBuilder(TextUtils.concat(s1, " is a Test\n"));
tvHistory.append(s4);

// fails - s2 looses the red colored "This"
s2 = new SpannableStringBuilder(s4);
tvHistory.append(s2);

// fails - s1 looses the red colored "This"
s1 = new SpannableStringBuilder(s4, 0, 10);
tvHistory.append(new SpannableStringBuilder(TextUtils.concat(s1, "\n")));

// works - N/A
s3 = new SpannableStringBuilder(s4, 10, s4.length());
tvHistory.append(s3);

// Works - sets "Test" to red
s3.setSpan(new ForegroundColorSpan(COLOR), 0, s3.length(), FLAGS);
tvHistory.append(s3);

// fails - nothing is red
s4 = new SpannableStringBuilder(TextUtils.concat(s1 , s3));
tvHistory.append(s4);

// fails - nothing is red
s4 = new SpannableStringBuilder();
s4.append(s1.append(s3));
tvHistory.append(s4);

// works - both "This" and "Test" are red
s4.setSpan(new ForegroundColorSpan(COLOR), 0, 4, FLAGS);
s4.setSpan(new ForegroundColorSpan(COLOR), 10, 14, FLAGS);
tvHistory.append(s4);

0 个答案:

没有答案