How to highlight filtered text in RecyclerView when using SearchView widget

后端 未结 4 1434
执念已碎
执念已碎 2020-12-30 16:44

How to highlight search text result in RecyclerView. I found some posts regarding Spannable TextView, but not sure where to implement in my case. Appreciate you can look an

4条回答
  •  一向
    一向 (楼主)
    2020-12-30 17:12

    As per accepted answer indexOf() is not working in case of string value is "Mumbai" same occurrences inside string. So here I have used "Pattern" and "Matcher" class to make it work. Also, I have added ".toLowerCase()" to make string with same case and query work on string as ignore case. If you no need of ignore case of query string, You can remove .toLowerCase() from this code snippet

      SpannableStringBuilder sb = new SpannableStringBuilder(desc);
            Pattern word = Pattern.compile(query.toLowerCase());
            Matcher match = word.matcher(desc.toLowerCase());
    
            while (match.find()) {
                ForegroundColorSpan fcs = new ForegroundColorSpan(
                        ContextCompat.getColor(context, R.color.colorPrimary)); //specify color here
                    sb.setSpan(fcs, match.start(), match.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            }
            viewHolders.text_view_title.setText(sb);
    

提交回复
热议问题