How to highlight the filtered text while using SearchView widget in android

后端 未结 3 1050
误落风尘
误落风尘 2021-02-15 07:30

I have implemented SearchView Widget in my app. Its working fine. Now i need to do is, whenever i type a word in my SearchView Bar

3条回答
  •  失恋的感觉
    2021-02-15 08:20

    you can use Spannable TextView for this. hope so this Method will help you

    Method:

    public static CharSequence highlightText(String search, String originalText) {
        if (search != null && !search.equalsIgnoreCase("")) {
            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 ForegroundColorSpan(Color.BLUE), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    start = normalizedText.indexOf(search, spanEnd);
                }
                return highlighted;
            }
        }
        return originalText;
    }
    

    and return originalText will highlight text.

提交回复
热议问题