101.android 简单的搜索时改变被搜索字段的字体颜色+搜索时改变被搜索字段的背景颜色

/**
 * 搜索关键字,字体颜色改变
 *
 * @param keyword
 * @param text
 * @return
 */
public SpannableStringBuilder keyWords(String keyword, String text) {
    String docInfo = text;
    int keywordIndex = text.indexOf(keyword);
    SpannableStringBuilder style = new SpannableStringBuilder(docInfo);
    while (keywordIndex != -1) {
        style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorAccent)), keywordIndex, keywordIndex + keyword.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        int tempkeywordTempIndex = keywordIndex + keyword.length();
        text = docInfo.substring(tempkeywordTempIndex);
        keywordIndex = text.indexOf(keyword);
        if (keywordIndex != -1) {
            keywordIndex += tempkeywordTempIndex;
        }
    }
    return style;
}

/**
 * 方法名:putBackgroundStr(String text, String seachText, Context context)
 * 功    能:搜索时改变被搜索字段的背景颜色
 * 参    数:String text, String seachText, Context context
 * 返回值:SpannableString
 */
public static SpannableString putBackgroundStr(String text, String seachText, Context context) {
    //text传的是当前item的全部string,seachText是传的搜索的string
    int keywordIndex = text.indexOf(seachText);
    SpannableString spanString = new SpannableString(text);
    BackgroundColorSpan span = new BackgroundColorSpan(context.getResources().getColor(R.color.colorAccent));
    spanString.setSpan(span, keywordIndex, keywordIndex + seachText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return spanString;
}

 

//例:

 

//第一步 activity_main_user.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <SearchView
        android:queryHint="搜索"
        android:iconifiedByDefault="false"
        android:background="#cac5c5"
        android:id="@+id/mSearchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- 为SearchView定义自动补齐的ListView-->
    <ListView
        android:id="@+id/mListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

//第二步 MainUserActivity代码:

package com.gang.app.myceshi;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.gang.app.myceshi.bean.User;

import java.util.ArrayList;
import java.util.List;

public class MainUserActivity extends AppCompatActivity {

    private List<User> mData = new ArrayList<User>();  // 这个数据会改变
    private List<User> mBackData;  // 这是原始的数据

    private ListView mListView;
    private SearchView mSearchView;
    private MyAdapter mAdapter;
    private String seachText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_user);
        mListView = (ListView) super.findViewById(R.id.mListView);
        mSearchView = (SearchView) super.findViewById(R.id.mSearchView);
        //添加数据
        initData();

        // 设置监听器
        mSearchView.setOnQueryTextListener(new QueryListener());
        mListView.setTextFilterEnabled(true);
        mListView.setOnItemClickListener(new ItemClick());
        //适配器
        mAdapter = new MyAdapter(this);
        mListView.setAdapter(mAdapter);
    }

    //我这里写的是死数据,也可以用User这个Bean类动态添加数据
    private void initData() {
        mData.add(new User(R.mipmap.ic_launcher, "张三"));
        mData.add(new User(R.mipmap.ic_launcher, "李四"));
        mData.add(new User(R.mipmap.ic_launcher, "王五"));
        mData.add(new User(R.mipmap.ic_launcher, "赵六"));
        //mBackData用来搜索框清空后回复到原始的数据
        mBackData = mData;
    }

    // 必须实现Filterable接口
    private class MyAdapter extends BaseAdapter implements Filterable {
        private MyFilter mFilter;
        private Context context;

        public MyAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = View.inflate(MainUserActivity.this, R.layout.item_layout, null);
            }

            TextView textView = (TextView) convertView.findViewById(R.id.mText);
            ImageView mImg = (ImageView) convertView.findViewById(R.id.mImg);
            mImg.setImageResource(mData.get(position).getImg());

            String name = mData.get(position).getName();

            //在这里设置搜索时变颜色
            if (!TextUtils.isEmpty(seachText)) {
                SpannableStringBuilder putstr = putstr(name, seachText, context);
                textView.setText(putstr);
//                SpannableString string = putBackgroundStr(name, seachText, MainUserActivity.this);
//                textView.setText(string);
            } else {
                textView.setText(name);
            }
            return convertView;
        }

        @Override
        public Filter getFilter() {
            if (null == mFilter) {
                mFilter = new MyFilter();
            }
            return mFilter;
        }

        // 自定义Filter类
        class MyFilter extends Filter {
            @Override
            // 该方法在子线程中执行
            // 自定义过滤规则
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();

                List<User> newValues = new ArrayList<User>();
                String filterString = constraint.toString().trim().toLowerCase();

                // 如果搜索框内容为空,就恢复原始数据
                if (TextUtils.isEmpty(filterString)) {
                    newValues = mBackData;
                } else {
                    // 过滤出新数据
                    for (int i = 0; i < mBackData.size(); i++) {
                        //通过这个判断进行过滤,通过mBackData.get(i).getName()进行过滤
                        if (-1 != mBackData.get(i).getName().toLowerCase().indexOf(filterString)) {
                            newValues.add(mBackData.get(i));
                        }
                    }
                }
                results.values = newValues;
                results.count = newValues.size();
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                mData = (List<User>) results.values;

                if (results.count > 0) {
                    mAdapter.notifyDataSetChanged();  // 通知数据发生了改变
                } else {
                    mAdapter.notifyDataSetInvalidated(); // 通知数据失效
                }
            }
        }
    }

    // 搜索文本监听器
    private class QueryListener implements SearchView.OnQueryTextListener {
        // 当内容被提交时执行
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        // 当搜索框内内容发生改变时执行
        @Override
        public boolean onQueryTextChange(String newText) {

            if (TextUtils.isEmpty(newText)) {
                mListView.clearTextFilter();  // 清楚ListView的过滤
                seachText = null;
            } else {
                mListView.setFilterText(newText); // 设置ListView的过滤关键词
                //隐藏弹出的黑框
                mListView.dispatchDisplayHint(View.INVISIBLE);
                seachText = newText;
            }
            return true;
        }
    }

    //ListView的item点击事件
    private class ItemClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(MainUserActivity.this, mData.get(position).getName(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 方法名:putstr(String keyword, String strtext, Context context)
     * 功    能:搜索时改变被搜索字段的字体颜色
     * 参    数:String keyword, String strtext, Context context
     * 返回值:SpannableStringBuilder
     */
    public static SpannableStringBuilder putstr(String strText, String keyWord, Context context) {
        //keyWord是传的搜索的string,strText传的是当前item的全部string
        String docInfo = strText;
        int keywordIndex = strText.indexOf(keyWord);
        SpannableStringBuilder style = new SpannableStringBuilder(docInfo);
        while (keywordIndex != -1) {
            /**
             * 关键字颜色改变
             */
            style.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.colorAccent)), keywordIndex, keywordIndex + keyWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            int tempkeywordTempIndex = keywordIndex + keyWord.length();
            strText = docInfo.substring(tempkeywordTempIndex, docInfo.length());
            keywordIndex = strText.indexOf(keyWord);
            if (keywordIndex != -1) {
                keywordIndex = keywordIndex + tempkeywordTempIndex;
            }
        }
        return style;
    }


    /**
     * 方法名:putBackgroundStr(String text, String seachText, Context context)
     * 功    能:搜索时改变被搜索字段的背景颜色
     * 参    数:String text, String seachText, Context context
     * 返回值:SpannableString
     */
    public static SpannableString putBackgroundStr(String text, String seachText, Context context) {
        //text传的是当前item的全部string,seachText是传的搜索的string
        int keywordIndex = text.indexOf(seachText);
        SpannableString spanString = new SpannableString(text);
        BackgroundColorSpan span = new BackgroundColorSpan(context.getResources().getColor(R.color.colorAccent));
        spanString.setSpan(span, keywordIndex, keywordIndex + seachText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanString;
    }

}

 //第三步 item_layout.xml : 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >

    <ImageView
        android:id="@+id/mImg"
        android:src="@mipmap/ic_launcher"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="100dp" />

    <TextView
        android:id="@+id/mText"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="100dp" />
    <TextView
        android:text="年龄18"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="100dp" />
    <TextView
        android:text="性别男"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="100dp" />
    <TextView
        android:text="北京"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="100dp" />

</LinearLayout>

 //第四步 User实体Bean类:

public class User {

    private int img;
    private String name;

    public User(int img, String name) {
        this.img = img;
        this.name = name;
    }

    public int getImg() {
        return img;
    }

    public void setImg(int img) {
        this.img = img;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 //--------------------------------------------------------------------------------完--------------------------------------------------------------------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值