如何在Android中使用SearchView小部件时突出显示过滤的文本 [英] How to highlight the filtered text while using SearchView widget in android

查看:76
本文介绍了如何在Android中使用SearchView小部件时突出显示过滤的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的应用中实现了 SearchView 小部件.它的工作正常.现在我需要做的是,每当我在 SearchView栏 中键入一个单词时,过滤后的结果应以高亮显示搜索到的单词.像:

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 , the filtered result should show the searched word highlighted. like:

我正在将此 SearchView 小部件用作:

I am using this SearchView widget as :

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.myMenu , menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView sv = new SearchView(getActivity());

    // Changing the color of Searchview widget text field to white.     
    int searchSrcTextId = getResources().getIdentifier("android:id/search_src_text", null, null);  
    EditText searchEditText = (EditText) sv.findViewById(searchSrcTextId);  
    searchEditText.setTextColor(Color.WHITE); 

    sv.setOnQueryTextListener(this);
    searchItem.setActionView(sv);
    super.onCreateOptionsMenu(menu, inflater);
}

推荐答案

,您可以为此使用Spannable TextView.希望这样可以帮助您

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

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

return originalText 将突出显示文本.

这篇关于如何在Android中使用SearchView小部件时突出显示过滤的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆