I have a String of sentence and a list of words that need to be highlighted if there is an occurrence in that String. How do I do that?
Asked
Active
Viewed 61 times
2 Answers
0
You can use Html.
for(String word: listString){
if(sentence.contains(word){
sentence = sentence.replace(word,"<font color='red'>"+word+"</font>");
}
}
mTextView.setText(Html.fromHtml(sentence));

Pr38y
- 1,565
- 13
- 21
-
The final string is highlighting only the word from last item in list. – roshanthejoker Apr 12 '17 at 17:45
-
my mistake. string is immutable class. – Pr38y Apr 12 '17 at 17:50
-
So do I save the result in each iteration? – roshanthejoker Apr 12 '17 at 17:54
-
no.. each iteration will give the result of updated value. until all iterations are done you won't get final result. I have updated the code, use the same. – Pr38y Apr 13 '17 at 06:38
0
I managed to do it with SpannableStringBuilder.
Here's the code:
@Override
public void renderFinalTranscript(final String transcript, String filler)
{
getActivity().runOnUiThread(() -> {
final Pattern p = Pattern.compile(filler);
final Matcher matcher = p.matcher(transcript);
SpannableStringBuilder sb = new SpannableStringBuilder(transcript);
while(matcher.find()){
sb.setSpan(CharacterStyle.wrap(new ForegroundColorSpan(Color.RED)), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
transcribeText.append(spanny);
});
}
I called this method in a for loop and got the intended result

roshanthejoker
- 13
- 6