AutoCompleteTextView
的自定义适配器始终返回所有项目。 results.count
始终是正确的尺寸,这就是我想知道的原因......
public class UniversityAdapter extends ArrayAdapter<University> implements Filterable {
List<University> items = new ArrayList<University>();
List<University> itemsAll = new ArrayList<University>();
private Context context;
int resource;
public UniversityAdapter(Context context, int resId, List<University> items) {
super(context, resId, items);
this.context = context;
this.resource = resId;
this.items = items;
itemsAll.addAll(this.items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(resource, parent, false);
} else {
row = convertView;
}
University university = itemsAll.get(position);
TextView nameView = (TextView) row.findViewById(android.R.id.text1);
nameView.setText(university.getName());
return row;
}
@Override
public Filter getFilter() {
return new Filter() {
public String convertResultToString(Object resultValue) {
String str = ((University) (resultValue)).getName();
return str;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
List<University> suggestions = new ArrayList<University>();
for (University university : itemsAll) {
if (university.getName().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
suggestions.add(university);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
items = (ArrayList<University>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
}
}
答案 0 :(得分:1)
我认为这段代码是罪魁祸首:
this.items = items;
itemsAll.addAll(this.items); //remove this, use only items
我建议完全删除itemsAll
,因为items
就足够了。
看看这段代码:
items = (ArrayList<University>) results.values;
notifyDataSetChanged();
您使用items
而不是itemsAll
更新
然后改变(参见我的comments
):
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
List<University> universities= (ArrayList<University>) results.values;
items.clear(); //clear the old data
for(University univ : universities)
{
items.add(univ); //add each result
}
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
获得理想的结果。