-1

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?

2 Answers2

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
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