Android: Colorize Matches внутри строкиJAVA

Программисты JAVA общаются здесь
Anonymous
Android: Colorize Matches внутри строки

Сообщение Anonymous »

Я хочу раскрасить все слова, начиная с #, + или @. Я нашел решения, чтобы соответствовать словам и раскрасить подстроки SpannableString, но это не работает правильно. Только последний матч окрашивается. Другие совпадения остаются невыполненными, но я не могу найти ошибку. < /P>

public static SpannableStringBuilder colorTags(Context cxt, String text){
final Pattern hashtag = Pattern.compile("#\\w+");
final Pattern at = Pattern.compile("(\\s|\\A)@(\\w+)");
final Pattern name = Pattern.compile("(\\s|\\A)\\+(\\w+)");

final SpannableStringBuilder spannable = new SpannableStringBuilder(text);

final ForegroundColorSpan at_color = new ForegroundColorSpan(cxt.getResources().getColor(R.color.orange));
final ForegroundColorSpan hash_color = new ForegroundColorSpan(cxt.getResources().getColor(R.color.light_blue));
final ForegroundColorSpan name_color = new ForegroundColorSpan(cxt.getResources().getColor(R.color.green));

final Matcher matcher = hashtag.matcher(text);
final Matcher at_matcher = at.matcher(text);
final Matcher name_matcher = name.matcher(text);

while (matcher.find()) {
spannable.setSpan(
hash_color, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}

while (at_matcher.find()) {
spannable.setSpan(
at_color, at_matcher.start(), at_matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}

while (name_matcher.find()) {
spannable.setSpan(
name_color, name_matcher.start(), name_matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
return spannable;
}


Подробнее здесь: https://stackoverflow.com/questions/251 ... hin-string

Вернуться в «JAVA»