I have a string that has specific words I want to color. Those words are the one's that start with #.
if(title.contains("#")){
SpannableString WordtoSpan = new SpannableString(title);
int idx = title.indexOf("#");
if (idx >= 0) {
Pattern pattern = Pattern.compile("[ ,\\.\\n]");
Matcher matcher = pattern.matcher(title);
int wordEnd = matcher.find(idx)? matcher.start() : -1;
if (wordEnd < 0) {
wordEnd = title.length();
}
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE),
idx,
wordEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
holder.txtTitle.setText(WordtoSpan);
} else {
holder.txtTitle.setText(title);
}
Now lets take for example this string Bold part is for example the colored words.
I love cheese #burgers, and with #ketchup.
^ This is my current thing with my code. What I want is to color every #
word, not just first one.
ex. It'll be like
I love cheese #burgers, and with #ketchup.
I think I need to loop? But couldn't get it clearly and working x.x
Update: Latest try. List becomes blank.
SpannableString WordtoSpan = new SpannableString(title);
int end = 0;
Pattern pattern = Pattern.compile("[ ,\\.\\n]");
Matcher matcher = pattern.matcher(title);
int i = title.indexOf("#");
for (i = 0; i < title.length(); i++) {
if (i >= 0) {
int wordEnd = matcher.find(i)? matcher.start() : -1;
if (wordEnd < 0) {
wordEnd = title.length();
}
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE),
i,
wordEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
i = end;
}
holder.txtTitle.setText(WordtoSpan);
}