Highlight searched text in ListView items

android, listview, search, string

Solution

I assume that you have a custom Adapter with `getCount()` and `getView()` implemented and already filtering items, and you just need the bold part.

To achieve that, you need to use a `SpannableString`, which is basically text with markup attached. For example, a `TextAppearanceSpan` can be used to change typeface, font style, size, and color.

So, you should update your adapter's `getView()` to change the part where you use `textView.setText()` into something more or less like this:

String filter = ...;
String itemValue = ...;

int startPos = itemValue.toLowerCase(Locale.US).indexOf(filter.toLowerCase(Locale.US));
int endPos = startPos + filter.length();

if (startPos != -1) // This should always be true, just a sanity check
{
    Spannable spannable = new SpannableString(itemValue);
    ColorStateList blueColor = new ColorStateList(new int[][] { new int[] {}}, new int[] { Color.BLUE });
    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);

    spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(spannable);
}
else
    textView.setText(itemValue);

Problem

I have a `ListView` and i am using a custom adapter to show data. Now i want to change searched text letter colour as in above screen shot. Here is the code for `SearchView` ``` @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.actionbar_menu_item, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); final SearchView searchView = (SearchView) menu.findItem(R.id.action_search) .getActionView(); searchView.setSearchableInfo(searchManager .getSearchableInfo(getComponentName())); searchView.setOnQueryTextListener(this); return super.onCreateOptionsMenu(menu); } public boolean onQueryTextChange(String newText) { // this is adapter that will be filtered if (TextUtils.isEmpty(newText)){ lvCustomList.clearTextFilter(); } else{ lvCustomList.setFilterText(newText.toString()); } return false; } @Override public boolean onQueryTextSubmit(String query) { return false; } ``` Thank you.

Original source

Related problems