how do I highlight the searched text in my search filter?

后端 未结 5 2370
无人及你
无人及你 2020-12-09 12:27

I am trying to do a search such that all the \"visible\" search letters should be highlighted. I tried using spannable but that didn\'t do the trick, maybe I wasnt doing it

5条回答
  •  忘掉有多难
    2020-12-09 12:36

    In your filter method, store the string used to perform the filter:

    // Filter Class
    public void filter(String searchString) {
        this.searchString = searchString;
        ...
        // Filtering stuff as normal.
    }
    

    You must declare a member string to store it:

    public class ListViewAdapter extends BaseAdapter {
        ...    
        String searchString = "";
        ...
    

    And, in getView you highlight the search term:

    public View getView(final int position, View view, ViewGroup parent) {
        ...
        // Set the results into TextViews
        WorldPopulation item = worldpopulationlist.get(position);
        holder.rank.setText(item.getRank());
        holder.country.setText(item.getCountry());
        holder.population.setText(item.getPopulation());
    
        // Find charText in wp
        String country = item.getCountry().toLowerCase(Locale.getDefault());
        if (country.contains(searchString)) {
            Log.e("test", country + " contains: " + searchString);
            int startPos = country.indexOf(searchString);
            int endPos = startPos + searchString.length();
    
            Spannable spanText = Spannable.Factory.getInstance().newSpannable(holder.country.getText()); // <- EDITED: Use the original string, as `country` has been converted to lowercase.
            spanText.setSpan(new ForegroundColorSpan(Color.RED), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    
            holder.country.setText(spanText, TextView.BufferType.SPANNABLE);
        }
        ...
    }
    

    Hope it helps.

提交回复
热议问题