【问题标题】:How high light search text in RecyclerView adapterRecyclerView 适配器中如何突出显示搜索文本
【发布时间】:2018-02-11 17:38:42
【问题描述】:

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

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

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;
    }

这是我在文本更改活动中的代码(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 回答结果没问题!

【问题讨论】:

标签: android highlight android-recyclerview


【解决方案1】:

在你的适配器中有一个 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 );

【讨论】:

  • 谢谢,但我不会更改 Moment(数据库模型),因为用于任何方法!
  • 添加另一个参数不应该影响您的其他模型。因为它没有必要改变你的其他方法的代码
  • @ghasemdeh 我已经更新了我的答案。它根据您的要求量身定制。请检查
  • 感谢亲爱的 Sahil ...但我需要高光搜索文本没有完整的文本
  • @ghasemdeh 您正在使用 textview 来显示文本吗?
猜你喜欢
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 2012-06-25
  • 2011-03-03
  • 1970-01-01
相关资源
最近更新 更多