1.布局的XML文件里面添加EditText控件(省略)控件id=mSearch ListView的id=admin_lv;
2.一、获取ListView展示的数据(通过适配器获取)
二、这个是我要说的搜索功能
mSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//这个和之前的适配器不同,是搜索完成后listview
madminAdapter = new AdminManagerAdapter(AdminActivity.this, adminList);
//搜索完获取的数据
madminAdapter.setDataSource(adminList);
admin_lv.setAdapter(madminAdapter);
madminAdapter.getFilter().filter(s);
if (s.length() > 0) {
admin_lv.setVisibility(View.VISIBLE);
} else {
admin_lv.setVisibility(View.GONE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
3.搜索适配的要实现:Filterable这个接口
代码如下:(其他适配的方法和之前的BaseAdapter是一样的)
//满足过滤条件的数据
private List<AdminMenager> mOriginalValues;
//过滤时候的总数据 这个是不变的数据
private List<AdminMenager> adminList;
//适配器的adpater
private List<AdminMenager> adapterList;
//初始化数据
public AdminManagerAdapter(Context context,List<AdminMenager> adminList) {
super(context);
this.adminList=adminList;
mOriginalValues=new ArrayList<>();
adapterList=new ArrayList<>();
adapterList.addAll(adminList);
}
@Override
public Filter getFilter() {
if (myFilter==null){
myFilter=new MyFilter();
}
return myFilter;
}
//过滤数据
class MyFilter extends Filter {
//执行过滤
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
mOriginalValues.clear();
results.values = adminList;
} else {
mOriginalValues.clear();
for (Iterator<AdminMenager> iterator = adminList.iterator(); iterator
.hasNext();) {
AdminMenager name = iterator.next();
if (name.user_name.contains(constraint)) {
mOriginalValues.add(name);
}
}
results.values = mOriginalValues;
}
Log.d("adapter","???result"+results);
return results;
}
//得到过滤结果
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapterList = (ArrayList<AdminMenager>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
注:此方法只用于搜索ListView展示的信息
祝大家好运连连