原创

Android Filter筛选ListView并且筛选内容变色

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://gaolei.blog.csdn.net/article/details/48898831

      转载请标明原地址:http://blog.csdn.net/gaolei1201/article/details/48898831

      微信中有筛选功能,且筛选内容会变色,感觉挺酷的,研究了一下,如图

      


我首先想到的是遍历每一个数据,如果包含就把它添加到List中,然后用SpannableStringBuilder 类使筛选的内容变色。后来发现系统有一个Filter类专一用来实现筛选的,挺好。这个类的好处就是封装了异步,结构类似AsyncTask,这样不用担心数据多而阻塞主线程了。别的不多说了,上代码:

MainActivity.java

<span style="font-size:14px;">public class MainActivity extends Activity {
	  private Context mContext;
	    private ListView mListView;
	    private ListViewAdapter mListViewAdapter;
	    private ArrayList<String> mArrayList;
	    private EditText search_edit;
	  @Override
	  protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	    init();
	  }

	  private void init(){
	    mContext=this;
	    mListView=(ListView) findViewById(R.id.listView);
	    search_edit=(EditText) findViewById(R.id.search_edit);
	    mArrayList=new ArrayList<String>();
	    mArrayList.add("张三1");
	    mArrayList.add("李四1");
	    mArrayList.add("王五1");
	    mArrayList.add("张三2");
	    mArrayList.add("李四2");
	    mArrayList.add("王五2");
	    mArrayList.add("张三3");
	    mArrayList.add("李四3");
	    mArrayList.add("王五3");
	    mArrayList.add("张三4");
	    mArrayList.add("李四4");
	    mArrayList.add("王五4");
	    mListViewAdapter=new ListViewAdapter(mContext, mArrayList);
	    //过滤数据
	    //过滤出姓名里面包含"张"的数据
	   
	    mListView.setAdapter(mListViewAdapter);
	    search_edit.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				 mListViewAdapter.getFilter().filter(arg0);
//               也可以在这里筛选数据,但这不是异步的,有隐患,最好用系统提供的Filter类				 
//				 for (Iterator<String> iterator = mArrayList.iterator(); iterator
//							.hasNext();) {
//						String name = iterator.next();
//
//						if (name.contains(arg0)) {
//							mFilteredArrayList.add(name);
//						}
//				 mListViewAdapter.changeList(mFilteredArrayList);
//				 mListViewAdapter.notifyDataSetChanged();
			}
	    	
	    });
	  }
	  public  void onDestroy(){
		  super.onDestroy();
		  ListViewAdapter.searchContent="";
	  }

	}</span>

ListViewAdapter.java

<span style="font-size:14px;">public class ListViewAdapter extends BaseAdapter {
	private NameFilter mNameFilter;
	private List<String> mArrayList, copyList;
	private List<String> mFilteredArrayList;
	private LayoutInflater mLayoutInflater;
	public static String searchContent;

	public ListViewAdapter(Context context, List<String> arrayList) {
		mArrayList = arrayList;
		mLayoutInflater = LayoutInflater.from(context);
		mFilteredArrayList = new ArrayList<String>();
		//copyList是暂存原来所用的数据,当筛选内容为空时,显示所有数据,并且必须new 一个对象,
		//而不能copyList=arrayList,这样的话当arrayList改变时copyList也就改变了
		copyList = new ArrayList<String>();
		copyList.addAll(arrayList);
	}

	@Override
	public int getCount() {
		if (mArrayList == null) {
			return 0;
		} else {
			return (mArrayList.size());
		}

	}

	@Override
	public Object getItem(int position) {
		if (mArrayList == null) {
			return null;
		} else {
			return mArrayList.get(position);
		}
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	public void changeList(List<String> arrayList){
		mArrayList=arrayList;
	}

	public Filter getFilter() {
		if (mNameFilter == null) {
			mNameFilter = new NameFilter();
		}
		return mNameFilter;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
			convertView = mLayoutInflater.inflate(R.layout.listview_items, null);
			viewHolder = new ViewHolder();
			viewHolder.textView = (TextView) convertView
					.findViewById(R.id.textView);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		if (mArrayList != null) {
			String name = mArrayList.get(position);
			viewHolder.textView.setText(name);
			if (searchContent != null) {
				if(name.indexOf(searchContent)!=-1){
				SpannableStringBuilder style = new SpannableStringBuilder(name);
				style.setSpan(
						new ForegroundColorSpan(Color.parseColor("#00cc00")),
						name.indexOf(searchContent),
						name.indexOf(searchContent) + searchContent.length(),
						Spannable.SPAN_EXCLUSIVE_INCLUSIVE); // 设置指定位置文字的颜色
				viewHolder.textView.setText(style);
			}
			}
		}

		return convertView;
	}

	private class ViewHolder {
		TextView textView;
	}

	// 异步过滤数据,避免数据多耗时长堵塞主线程
	class NameFilter extends Filter {
		// 执行筛选
		@Override
		protected FilterResults performFiltering(CharSequence charSequence) {
			searchContent = charSequence.toString();
			FilterResults filterResults = new FilterResults();
			if (charSequence == null|| charSequence.length() == 0) {
				mFilteredArrayList = copyList;
			} else {
				mFilteredArrayList.clear();
				for (Iterator<String> iterator = copyList.iterator(); iterator
						.hasNext();) {
					String name = iterator.next();

					if (name.contains(charSequence)) {
						mFilteredArrayList.add(name);
					}
				}
			}
			filterResults.values = mFilteredArrayList;
			return filterResults;
		}

		// 筛选结果
		@Override
		protected void publishResults(CharSequence arg0, FilterResults results) {
			mArrayList = (List<String>) results.values;
			if (mArrayList.size() > 0) {
				notifyDataSetChanged();
			} else {
				notifyDataSetInvalidated();
			}

		}
	}

}</span>

效果图:



                                


                代码地址,欢迎光临.......................

                                       





文章最后发布于: 2015-10-04 20:06:01
展开阅读全文
0 个人打赏
私信求帮助

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览