I have a listview with some items that can be marked as \"done\". There is also a togglebutton that says \"hide done items\".
However, when I do hide the items by s
I was able to solve this problem using Knickedi's solution and the comments under it. Just wanted to show my relatively complete adapter to clarify it a bit.
I have the class StockItem with fields to hold a range of data for a single stock item. For the custom ArrayAdapter, the constructor takes the complete list of StockItems retrieved from a database table, and any add/remove methods I may add in the future will also operate on this list (mList). However, I overrode getView(), and getCount() to read from a second list (mFilteredList) produced using the method filterList():
public class StockItemAdapter extends ArrayAdapter {
...
ArrayList mList;
ArrayList mFilteredList;
public StockItemAdapter(Context context, int resource, ArrayList list) {
super(context, resource, list);
...
mList = list;
mFilteredList = list;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
StockItemHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
row = inflater.inflate(mResource, parent, false);
holder = new StockItemHolder();
holder.imageView = (ImageView)row.findViewById(R.id.imageView);
...
row.setTag(holder);
} else {
holder = (StockItemHolder)row.getTag();
}
StockItem stockItem = mFilteredList.get(position);
if (stockItem.getImage() != null) {
holder.imageView.setImageBitmap(stockItem.getImage());
} else {
holder.imageView.setImageResource(R.drawable.terencephilip);
}
...
return row;
}
@Override
public int getCount() {
return mFilteredList.size();
}
static class StockItemHolder {
ImageView imageView;
...
}
public void filterList(String search) {
mFilteredList = new ArrayList();
for (StockItem item : mList) {
if (item.getDescription().toLowerCase(Locale.ENGLISH)
.contains(search.toLowerCase(Locale.ENGLISH))) {
mFilteredList.add(item);
}
}
notifyDataSetChanged();
}
}
filterList(String search) is called from an OnQueryTextListener and removes list items whose descriptions don't match the entered text.
In the case of a large list, filterList() may be a problem on the main thread, but that is irrelevant for this question.
EDIT: The getItem(position) method must also be overridden to return the item from mFilteredList.
@Override
public StockItem getItem(int position) {
return mFilteredList.get(position);
}