How to find a word in a string and highlight a word in a text representation in android?

in my android app, I have a line containing a specific word, so I want to display the whole line in a text view, and a specific word should be highlighted. We hope that the following image will give you an idea.

enter image description here

I used the following code for this, but did not work.

CODE:

con is my string, and groupNameContent is a text field.

con.replaceAll(arrGroupelements[groupPosition][5],"<font color='#CA278C'>"+arrGroupelements[groupPosition][5]+"</font>."); groupNameContent.setText(Html.fromHtml(con)); 
+7
source share
2 answers

for each word, you can use:

 TextView textView = (TextView)findViewById(R.id.mytextview01); //use a loop to change text color Spannable WordtoSpan = new SpannableString("partial colored text"); WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(WordtoSpan); 
+7
source

If I can understand that you have a list of words, and you want to find these words in the text and highlight them, so in this answer you have three input parameters:

  • full text.
  • yourList
  • yourTextview to display the result text

     String text = "full of your text"; Spannable textSpannable = new SpannableString(text); for (int j =0 ; j<yourList.size() ; j++) { //word of your list String word = String.valueOf(yourList.get(j)); //find index of words for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) { //find the length of word for set color int last = i + word.length(); //set text color with spannable textSpannable.setSpan(new BackgroundColorSpan(Color.parseColor("#0cab8f")), i, last, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } yourTextView.setText(textSpannable); 
+3
source

All Articles