Android - Highlight a Word In a TextView?

iTurki picture iTurki · Jul 27, 2011 · Viewed 32.6k times · Source

I have a database search query which search in the database for a word entered by the user and return a Cursor.

In my ListActivity, I have a ListView which will hold the items (the Cursor items). The ListView items layout is basically a TextView. I mean, the ListView will be a list of TextView's.

What I want is to highlight the search term wherever it appears in the TextView. I mean by highlighting: different color or different background color or anything makes it different than the rest of the text.

Is this possible? and how?

Update:

cursor = myDbHelper.search(term);  //term: a word entered by the user.
cursor.moveToFirst();
String[] columns = {cursor.getColumnName(1)}; 
int[] columnsLayouts = {R.id.item_title}; //item_title: the TextView holding the one raw
ca = new SimpleCursorAdapter(this.getBaseContext(), R.layout.items_layout, cursor,columns , columnsLayouts);
lv = getListView();
lv.setAdapter(ca);

For @Shailendra: The search() method will return some titles. I want to highlight the words in those titles that matches the term word. I hope this is clear now.

Answer

Shailendra Singh Rajawat picture Shailendra Singh Rajawat · Jul 27, 2011

insert HTML code for color around word and set it to your textView .

like

String newString = oldString.replaceAll(textToHighlight, "<font color='red'>"+textToHighlight+"</font>");
textView.setText(Html.fromHtml(newString));