我使用的是使用SpannableStringBuilder的代码。但是我的主要字符串中有很多模式。使用这些代码我只需更改最后找到的模式。这是我的代码:
final Pattern ptn = Pattern.compile("java"); // i have 9 "java" in my string
final Matcher matcher = ptn.matcher(getString(R.string.test2));
final SpannableStringBuilder spannable = new SpannableStringBuilder(getString(R.string.test));
final ForegroundColorSpan span = new ForegroundColorSpan(Color.GREEN);
while (matcher.find()) {
spannable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
txtView.setText(spannable);
我不知道mu问题在哪里?
答案 0 :(得分:5)
尝试为每个循环创建跨度,如下所示:
final Pattern ptn = Pattern.compile("java"); // i have 9 "java" in my string
final Matcher matcher = ptn.matcher(getString(R.string.test2));
final SpannableStringBuilder spannable = new SpannableStringBuilder(getString(R.string.test));
while (matcher.find()) {
final ForegroundColorSpan span = new ForegroundColorSpan(Color.GREEN);
spannable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
txtView.setText(spannable);