我怎么突出我的搜索过滤器搜索到的文字? [英] how do I highlight the searched text in my search filter?

查看:225
本文介绍了我怎么突出我的搜索过滤器搜索到的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个搜索,使得所有的看得见的搜索字母应该加以强调。我试着用spannable,但没有做的伎俩,也许我不是这样做对吗?在此基础上:<一href=\"http://stackoverflow.com/questions/23905028/highlight-searched-text-in-listview-items\">Highlight在ListView中搜索项目文本
我要如何突出可见文本?这里是我的过滤器:

 私人LayoutInflater mInflater;        私人ValueFilter valueFilter;        公共MySimpleArrayAdapter(Activity上下文){            this.context =背景;
            mInflater = LayoutInflater.from(上下文);        }
        私有类ValueFilter扩展过滤器{
            //在辅助线程调用根据约束来过滤数据。
            @覆盖
            保护同步FilterResults performFiltering(CharSequence的约束){                FilterResults结果=新FilterResults();                如果(约束=空&放大器;!&放大器; constraint.length()大于0){                    ArrayList的&LT;整数GT; filterList =新的ArrayList&LT;&GT;();                    INT ICNT = listItemsHolder.Names.size();
                    的for(int i = 0; I&LT; ICNT;我++){
                        如果(listItemsHolder.Types.get(ⅰ)的ToString()的indexOf(HEADER _)方式&gt; -1){
                            继续;
                        }
                        如果(listItemsHolder.Names.get(i).matches(getRegEx(constraint))||(listItemsHolder.Names.get(i).toLowerCase().contains(constraint.toString().toLowerCase()))) {
                            如果(filterList.contains(i))的
                                继续;                            filterList.add(ⅰ);                        }
                        }                    results.count = filterList.size();                    results.values​​ = filterList;
                }其他{
                字符串prefixString = getRegEx(约束);
                mSearchText = prefixString;
                    results.count = listItemsHolder.Names.size();                    ArrayList的&LT;整数GT; TLIST =新的ArrayList&LT;&GT;();
                    的for(int i = 0; I&LT; results.count;我++){
                        tList.add(ⅰ);
                    }                    results.values​​ = TLIST;                }                返回结果;
}
                //在UI线程中调用发布在用户界面中过滤结果。
                @燮pressWarnings(未登记)
                @覆盖
                保护无效publishResults(CharSequence的约束,FilterResults结果){
                    ArrayList的&LT;整数GT; resultsList =(ArrayList的&LT;整数GT;)results.values​​;
                    如果(resultsList!= NULL){
                        m_filterList = resultsList;
                    }
                    notifyDataSetChanged();
                }            }            公共字符串getRegEx(CharSequence的元素){
                字符串结果=(我?)。*;
                对于(字符串元素:elements.toString()分裂(\\\\ S)){
                    结果+ =元素+*;
                }
                结果+ =*;
                返回结果;
            }提前致谢!

下面是我的getview

  @覆盖
        公共查看getView(INT位置,查看convertView,父母的ViewGroup){
            查看rowView = convertView;
            ViewHolder持有人;
            如果(过滤和放大器;&安培; m_filterList = NULL&放大器;!&安培; m_filterList.size()&GT;的位置)
                位置= m_filterList.get(位置);            如果(rowView == NULL){
                持有人=新ViewHolder();                mInflater = context.getLayoutInflater();
                rowView = mInflater.inflate(R.layout.rowlayout,NULL);
                //配置视图架
                holder.text =(TextView中)rowView.findViewById(R.id.label);
                holder.text.setTextColor(Color.WHITE);
                holder.text.setSingleLine();
                holder.text.setTextSize(15);
                holder.text.setEllipsize(TextUtils.TruncateAt.END);
                holder.text.setPadding(2,2,6,2);
                字样的标签= Typeface.createFromAsset(holder.text.getContext()。getAssets()
                        字体/宋体 - bold.ttf);
                holder.text.setTypeface(标签);
                holder.image =(ImageView的)rowView.findViewById(R.id.icon);
                holder.image.setPadding(6,4,0,4);
                。holder.image.getLayoutParams()=身高(INT)getResources()getDimension(R.dimen.icon_width_height);
                。holder.image.getLayoutParams()宽度=(int)的getResources()getDimension(R.dimen.icon_width_height);
                rowView.setBackgroundResource(R.drawable.row_border);
                rowView.setPadding(2,2,6,2);
                rowView.setTag(保持器);
            }其他{                //填写数据
                支架=(ViewHolder)rowView.getTag();
            }            字符串ID = listItemsHolder.getid(位置);
            字符串名称= listItemsHolder.getName(位置);
            holder.image.setVisibility(View.VISIBLE);
            如果(名字!= NULL){
                holder.text.setText(listItemsHolder.getName(位置));
                ViewGroup.MarginLayoutParams PARAMS =(ViewGroup.MarginLayoutParams)holder.text.getLayoutParams();
                params.leftMargin = 20;
            }其他{
                holder.text.setText(ID);
            }
            串全文= listItemsHolder.getName(位置);
            //亮点搜索文本
            如果(mSearchText =空&放大器;!&放大器;!mSearchText.isEmpty()){
                INT startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
                INT endPos = startPos + mSearchText.length();
                如果(startPos!= -1){
                    Spannable spannable =新SpannableString(全文)
                    ColorStateList blueColor =新ColorStateList(新INT [] [] {新INT [] {}},新的INT [] {Color.BLUE});
                    TextAppearanceSpan highlightSpan =新TextAppearanceSpan(NULL,Typeface.BOLD,-1,blueColor,NULL);
                    spannable.setSpan(highlightSpan,startPos,endPos,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.text.setText(spannable);
                }其他{
                    holder.text.setText(全文)
                }
            }其他{
                holder.text.setText(全文)
            }
            返回rowView;
        }


解决方案

让我们假设你有创建一个自定义适配器,那么你可以参考以下code:

  @覆盖
    公共查看getView(INT位置,查看convertView,父母的ViewGroup){
        查看视图。
        TextView的文本;        如果(convertView == NULL){
            鉴于= mInflater.inflate(mResource,父母,假);
        }其他{
            鉴于= convertView;
        }        尝试{
            如果(mFieldId == 0){
                //如果没有自定义字段分配,假定整个资源是一个TextView
                文字=(TextView的)视图。
            }其他{
                //否则,找到布局中的TextView场
                文字=(TextView的)view.findViewById(mFieldId);
            }
        }赶上(抛出ClassCastException E){
            Log.e(ArrayAdapter,你必须提供一个TextView资源ID);
            抛出新IllegalStateException异常(
                    ArrayAdapter需要的资源ID是一个TextView,E);
        }
        字符串项=的getItem(位置);
        text.setText(项目);        串全文=的getItem(位置);
        //亮点搜索文本
        如果(mSearchText =空&放大器;!&放大器;!mSearchText.isEmpty()){
            INT startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
            INT endPos = startPos + mSearchText.length();            如果(startPos!= -1){
                Spannable spannable =新SpannableString(全文)
                ColorStateList blueColor =新ColorStateList(新INT [] [] {新INT [] {}},新的INT [] {Color.BLUE});
                TextAppearanceSpan highlightSpan =新TextAppearanceSpan(NULL,Typeface.BOLD,-1,blueColor,NULL);
                spannable.setSpan(highlightSpan,startPos,endPos,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setText(spannable);
            }其他{
                text.setText(全文)
            }
        }其他{
            text.setText(全文)
        }        返回视图。
    }

mSearchText 将在 ArrayFilter performFiltering 以下更新C $ C>类。

 字符串prefixString = prefix.toString()与toLowerCase()。
mSearchText = prefixString;

您可以找到更多的细节我的样本code 我的GitHub(与介绍最新更新)

下面是截图

在这里输入的形象描述

I am trying to do a search such that all the "visible" search letters should be highlighted. I tried using spannable but that didn't do the trick, maybe I wasnt doing it right? based on this: Highlight searched text in ListView items How do i get to highlight the visible text? here's my filter :

private LayoutInflater mInflater;

        private ValueFilter valueFilter;

        public MySimpleArrayAdapter(Activity context) {

            this.context = context;
            mInflater = LayoutInflater.from(context);

        }
        private class ValueFilter extends Filter {


            //Invoked in a worker thread to filter the data according to the constraint.
            @Override
            protected synchronized FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();

                if (constraint != null && constraint.length() > 0) {

                    ArrayList<Integer> filterList = new ArrayList<>();

                    int iCnt = listItemsHolder.Names.size();
                    for (int i = 0; i < iCnt; i++) {
                        if(listItemsHolder.Types.get(i).toString().indexOf("HEADER_")>-1){
                            continue;
                        }
                        if (listItemsHolder.Names.get(i).matches(getRegEx(constraint))||(listItemsHolder.Names.get(i).toLowerCase().contains(constraint.toString().toLowerCase()))) {
                            if(filterList.contains(i))
                                continue;

                            filterList.add(i);

                        }
                        }

                    results.count = filterList.size();

                    results.values = filterList;
                }else {
                String prefixString = getRegEx(constraint);
                mSearchText = prefixString;
                    results.count = listItemsHolder.Names.size();

                    ArrayList<Integer> tList = new ArrayList<>();
                    for(int i=0;i<results.count;i++){
                        tList.add(i);
                    }

                    results.values = tList;

                }

                return results;


}


                //Invoked in the UI thread to publish the filtering results in the user interface.
                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    ArrayList<Integer> resultsList = (ArrayList<Integer>)results.values;
                    if(resultsList != null) {
                        m_filterList = resultsList;
                    }
                    notifyDataSetChanged();
                }

            }

            public String getRegEx(CharSequence elements){
                String result = "(?i).*";
                for(String element : elements.toString().split("\\s")){
                    result += element + ".*";
                }
                result += ".*";
                return result;
            }

Thanks in advance! 

Here's my getview

@Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View rowView = convertView;
            ViewHolder holder;
            if(filtering && m_filterList != null && m_filterList.size() > position)
                position = m_filterList.get(position);

            if (rowView == null) {
                holder = new ViewHolder();

                mInflater = context.getLayoutInflater();
                rowView = mInflater.inflate(R.layout.rowlayout, null);
                // configure view holder
                holder.text = (TextView) rowView.findViewById(R.id.label);
                holder.text.setTextColor(Color.WHITE);
                holder.text.setSingleLine();
                holder.text.setTextSize(15);
                holder.text.setEllipsize(TextUtils.TruncateAt.END);
                holder.text.setPadding(2, 2, 6, 2);
                Typeface label = Typeface.createFromAsset(holder.text.getContext().getAssets(),
                        "fonts/arial-bold.ttf");
                holder.text.setTypeface(label);
                holder.image = (ImageView) rowView.findViewById(R.id.icon);
                holder.image.setPadding(6, 4, 0, 4);
                holder.image.getLayoutParams().height = (int) getResources().getDimension(R.dimen.icon_width_height);
                holder.image.getLayoutParams().width = (int) getResources().getDimension(R.dimen.icon_width_height);
                rowView.setBackgroundResource(R.drawable.row_border);
                rowView.setPadding(2, 2, 6, 2);
                rowView.setTag(holder);
            }else {

                // fill data
                holder = (ViewHolder) rowView.getTag();
            }

            String id  = listItemsHolder.getid(position);
            String name = listItemsHolder.getName(position);
            holder.image.setVisibility(View.VISIBLE);


            if (name != null) {
                holder.text.setText(listItemsHolder.getName(position));
                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) holder.text.getLayoutParams();
                params.leftMargin = 20;
            }else{
                holder.text.setText(id);
            }
            String fullText = listItemsHolder.getName(position);
            // highlight search text
            if (mSearchText != null && !mSearchText.isEmpty()) {
                int startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
                int endPos = startPos + mSearchText.length();
                if (startPos != -1) {
                    Spannable spannable = new SpannableString(fullText);
                    ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
                    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
                    spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.text.setText(spannable);
                } else {
                    holder.text.setText(fullText);
                }
            } else {
                holder.text.setText(fullText);
            }
            return rowView;
        }

解决方案

Let's assume you have create a custom adapter, then you can refer to the following code:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        TextView text;

        if (convertView == null) {
            view = mInflater.inflate(mResource, parent, false);
        } else {
            view = convertView;
        }

        try {
            if (mFieldId == 0) {
                //  If no custom field is assigned, assume the whole resource is a TextView
                text = (TextView) view;
            } else {
                //  Otherwise, find the TextView field within the layout
                text = (TextView) view.findViewById(mFieldId);
            }
        } catch (ClassCastException e) {
            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
            throw new IllegalStateException(
                    "ArrayAdapter requires the resource ID to be a TextView", e);
        }
        String item = getItem(position);
        text.setText(item);

        String fullText = getItem(position);
        // highlight search text
        if (mSearchText != null && !mSearchText.isEmpty()) {
            int startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
            int endPos = startPos + mSearchText.length();

            if (startPos != -1) {
                Spannable spannable = new SpannableString(fullText);
                ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
                TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
                spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setText(spannable);
            } else {
                text.setText(fullText);
            }
        } else {
            text.setText(fullText);
        }

        return view;
    }

The mSearchText will be updated at the following inside performFiltering of ArrayFilter class.

String prefixString = prefix.toString().toLowerCase();
mSearchText = prefixString;

You can find more details in my sample code here or my GitHub (with lastest update).

Here is the screenshot

这篇关于我怎么突出我的搜索过滤器搜索到的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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