Fix ForegroundColorSpan Search Text Highlighting with RecyclerView and ListAdapter
Issue
Highlighing search text with Color.GREEN using ForegroundColorSpan is inconsistent within a RecyclerView using ListAdapter. Some items in the list are not highlighted, or only highlighted after scrolling.
Cause
ListAdapter uses asynchronous updates, and the dataset may not be ready when onBindViewHolder() is called. As a result, the searchString is not available to apply the highlighting correctly.
Solution
Update the Card model to include the searchString property. During filtering, create a new Card instance with the updated searchString. This will trigger the onBindViewHolder() method and apply the highlighting correctly.
// In MainActivity private void filter(String searchText) { ArrayList<Card> searchList = new ArrayList<>(); for (Card cardItem : mCards) { if (cardItem.getTodo().toLowerCase().contains(searchText.toLowerCase(Locale.US))) { searchList.add(new Card(cardItem.getTodo(), searchText)); // Create a new Card with updated searchString } } if (!searchList.isEmpty()) { adapter.submitList(searchList); // Submit the new Card list } }
// In CardRVAdapter public void setFilter(List<Card> newSearchList, String adapSearchText) { if (newSearchList != null && !newSearchList.isEmpty()) { ArrayList<Card> tempList = new ArrayList<>(newSearchList); submitList(tempList); } }
The above is the detailed content of Why is ForegroundColorSpan Search Text Highlighting Inconsistent in RecyclerView with ListAdapter?. For more information, please follow other related articles on the PHP Chinese website!