如何在 RecyclerView 适配器中高亮搜索文本

How high light search text in RecyclerView adapter

我在我的应用程序中使用了 RecyclerView 和自定义适配器...适配器实现了 Filterable 以进行搜索。如何设置高亮搜索文字?

这是我在自定义适配器中可过滤的代码:

private Filter filterResult = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults filterResults = new FilterResults();
            ArrayList<Moment> tempList = new ArrayList<>();
            if (MOMENT_FILTER != null) {
                if (TextUtils.isEmpty(constraint)) {
                    tempList = (ArrayList<Moment>) MOMENT_FILTER;
                } else {
                    int length = MOMENT_LIST.size();
                    int i = 0;
                    while (i < length) {
                        Moment item = MOMENT_FILTER.get(i);
                        if (item.getMoment().contains(constraint))
                            tempList.add(item);
                        i++;
                    }
                }
            }
            filterResults.values = tempList;
            filterResults.count = tempList.size();
            return filterResults;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            MOMENT_LIST = (ArrayList<Moment>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            }
        }
    };

    @Override
    public Filter getFilter() {
        return filterResult;
    }

这是我在 activity 中用于文本更改 (EditText) 的代码:

EDT_SEARCH.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
});

Sahil 回答结果还可以!

在您的适配器中引用 searchText 然后在你的 OnBindViewHolder 中你可以做

String text = list.get(position).getText(); // Your getter Method
String htmlText = text.replace(searchText,"<font color='#c5c5c5'>"+searchText+"</font>");
// Only searchText would be displayed in a different color.
holder.textView.setText(Html.fromHtml(htmlText );