Search code examples
androidtextview

How to search for a word in a string and highlight word in a text view in android?


in my android application i have a string that contains a specific word so i want to display whole string in text view and the specific word should be highlighted.Hope following image will give you an idea.

enter image description here

I have used following code to do this but its not working.

CODE:

con is my string and groupNameContent is the text field.

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

Solution

  • 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);