AutoCompleteTextView结合自定义过滤器
实现数据过滤,记录一下,方便以后使用。
自定义BaseAdapter 并实现Filterable接口
public class ListAdapter extends BaseAdapter implements Filterable {
private List<User> list;
private Context context;
private PersonFilter filter;
public ListAdapter(List<User> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
User p = list.get(position);
View view = LayoutInflater.from(context).inflate(R.layout.view, null);
TextView firstname = (TextView)view.findViewById(R.id.phone);
TextView lastname = (TextView)view.findViewById(R.id.time);
firstname.setText(p.getPhone());
lastname.setText(p.getTime());
return view;
}
@Override
public Filter getFilter() {
if (filter == null) {
filter = new PersonFilter(list);
}
return filter;
}
private class PersonFilter extends Filter {
private List<User> users;
public PersonFilter(List<User> list) {
this.users = list;
}
//这里是子线程来进行工作的
@Override
protected Filter.FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
results.values = users;
results.count = users.size();
} else {
List<User> mList = new ArrayList<>();
for (User p: users) {
if (p.getPhone().startsWith(constraint.toString())
|| p.getTime().startsWith(constraint.toString())) {
mList.add(p);
}
}
results.values = mList;
results.count = mList.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (List<User>)results.values;
notifyDataSetChanged();
}
}
}
user数据类
public class User{
private String phone;
private String time;
public String getPhone(){
return phone;
}
public String getTime(){
return time;
}
public void setPhone(String phone){
this.phone = phone;
}
public void setTime(String time){
this.time = time;
}
}
给AutoCompleteTextView设置,完工。
AutoCompleteTextView auto = (AutoCompleteTextView) findViewById(R.id.auto_complete);
List<User> users = new ArrayList<>();
User user = new User();
User user1 = new User();
User user2 = new User();
user.setPhone("18624915319");
user.setTime("12:00");
user1.setPhone("13928940420");
user1.setTime("8:00");
user2.setPhone("199883234204");
user2.setTime("10:08");
users.add(user1);
users.add(user);
users.add(user2);
auto.setAdapter(new ListAdapter(users, this));
网友评论