我已经编辑了我的 Adapter 类并扩展了可过滤类。我的搜索功能有效,但如果我退格搜索菜单中的所有内容,我将无法返回原始内容。
这是我的适配器类:
public class Menu_List_Item_Adapter extends BaseAdapter implements Filterable {
Context context;
List<FoodMenuRowItem> rowItems;
public Menu_List_Item_Adapter(Context context, List<FoodMenuRowItem> items) {
this.context = context;
this.rowItems = items;
}
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.food_menu_item_list_row,
null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.price);
holder.txtTitle = (TextView) convertView
.findViewById(R.id.description);
holder.imageView = (ImageView) convertView.findViewById(R.id.img);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FoodMenuRowItem rowItem = (FoodMenuRowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
@Override
public int getCount() {
return rowItems.size();
}
@Override
public Object getItem(int position) {
return rowItems.get(position);
}
@Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
@Override
public Filter getFilter() {
return new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results.count == 0)
notifyDataSetInvalidated();
else {
rowItems = (List<FoodMenuRowItem>) results.values;
Menu_List_Item_Adapter.this.notifyDataSetChanged();
}
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = rowItems;
results.count = rowItems.size();
} else { // We perform filtering operation
List<FoodMenuRowItem> filteredRowItems = new ArrayList<FoodMenuRowItem>();
for (FoodMenuRowItem p : rowItems) {
if (p.getName()
.toUpperCase()
.startsWith(constraint.toString().toUpperCase())) {
filteredRowItems.add(p);
}
}
results.values = filteredRowItems;
results.count = filteredRowItems.size();
}
return results;
}
};
}
}
我确实检查结果是零还是空,如果是的话返回原始列表?我错过了什么?