public class CustomAdapter extends ArrayAdapter
private ArrayList originalItems;
private ArrayList filteredItems;
public CustomAdapter(Context context, int resource, ArrayList items) {
super(context, resource, items);
this.originalItems = items;
this.filteredItems = items;
}
@Override
public int getCount() {
return filteredItems.size();
}
@Override
public String getItem(int position) {
return filteredItems.get(position);
}
@Override
public long getItemId(int position) {
return position; // 返回正确的项
}
@Override
public int getItemViewType(int position) {
return 0; // 返回正确的布局类型
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) { // 执行过滤操作
FilterResults results = new FilterResults();
if (TextUtils.isEmpty(constraint)) { // 如果搜索条件为空,返回原始数据
results.count = originalItems.size();
results.values = originalItems;
} else { // 否则过滤数据
ArrayList filteredList = new ArrayList<>();
for (String item : originalItems) {
if (item.toLowerCase().contains(constraint.toString().toLowerCase())) {
filteredList.add(item);
}
}
results.count = filteredList.size();
results.values = filteredList;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) { // 更新数据
filteredItems = (ArrayList) results.values;
notifyDataSetChanged();
}
};
}
}
上一篇:AutoCompleteTextView适配器导致资源编译错误
下一篇:AutoCompleteTextView使用MergeCursor从SearchRecentSuggestionsProvider显示错误的字符串。