如何在android studio中的文本监听器中突出显示已过滤的listView中的文本?

时间:2017-06-16 05:39:17

标签: java android listview addtextchangedlistener

我已经浏览了各种链接,其中突出显示了textview,但我需要它列表。

我的搜索方法:

public void addTextListener() {

        inputSearchMain.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

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

            public void onTextChanged(CharSequence query, int start, int before, int count) {

                query = query.toString().toLowerCase();

                final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();


                for (int i = 0; i < result_Category.size(); i++) {

                    final String text = result_Category.get(i).getCategory_name().toLowerCase();
                    if (text.contains(query)) {
                        //if(text.startsWith(query)

                        filteredList.add(result_Category.get(i));

                    }
                }

                mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
                mainAdapter = new RecyclerViewAdapterMain(filteredList);
                mainRecyclerView.setAdapter(mainAdapter);
                mainAdapter.notifyDataSetChanged();  // data set changed
            }
        });
    }

如何使用以下代码突出显示列表中的文字?

我想使用的代码:

public static CharSequence highlight(String search, String originalText) {
        String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
        int start = normalizedText.indexOf(search);
        if (start <= 0) {
            return originalText;
        } else {
            Spannable highlighted = new SpannableString(originalText);
            while (start > 0) {
                int spanStart = Math.min(start, originalText.length());
                int spanEnd = Math.min(start + search.length(), originalText.length());
                highlighted.setSpan(new BackgroundColorSpan(Color.YELLOW), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                start = normalizedText.indexOf(search, spanEnd);
            }
            return highlighted;
        }
    }

0 个答案:

没有答案