mFilteredList = new ArrayList(items);
Custom filter for the array adapter in android
-
25-06-2023 - |
Question
public class SpotAdapter extends ArrayAdapter<Spot> {
private ArrayList<Spot> mFilteredList, mUnfilteredList;
private Filter mFilter;
public SpotAdapter(Context context, int resource, List<Spot> items) {
super(context, resource, items);
mUnfilteredList = (ArrayList<Spot>) items;
mFilteredList = (ArrayList<Spot>) items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.record_row, null);
}
Spot p = (Spot) mFilteredList.get(position);
if (p != null) {
TextView nameView = (TextView) v.findViewById(R.id.name);
TextView addressView = (TextView) v.findViewById(R.id.address);
TextView typeView = (TextView) v.findViewById(R.id.type);
TextView contactView = (TextView) v.findViewById(R.id.contact);
ImageView starBtn = (ImageView) v.findViewById(R.id.star);
contactView.setVisibility(View.GONE);
nameView.setText(p.name);
addressView.setText(p.address);
typeView.setText(p.type == 1 ? "Leisure" : "Shopping");
starBtn.setTag("" + p.id);
starBtn.setVisibility(p.isStar ? View.VISIBLE : View.GONE);
}
return v;
}
@Override
public Filter getFilter() {
if(mFilter == null) {
mFilter = new Filter() {
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mFilteredList = (ArrayList<Spot>)results.values;
clear();
int count = mFilteredList.size();
for (int i=0; i<count; i++)
{
Spot s = (Spot)mFilteredList.get(i);
add(s);
}
//
// mFilteredList = (ArrayList<Spot>)results.values;
// notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
Log.d("test1","c "+constraint);
Log.d("test1","s "+mUnfilteredList.size());
FilterResults results = new FilterResults();
ArrayList<Spot> newList = new ArrayList<Spot>();
for (Spot obj : mUnfilteredList) {
// Compare the custom object and add to list if match
if (constraint.equals("bookmark")) {
if (obj.isStar == true)
newList.add(obj);
} else if (constraint.equals("select all")) {
newList.add(obj);
}
}
Log.d("test1",""+newList.size());
results.values = newList;
results.count = newList.size();
return results;
}
};
}
return mFilter;
}
}
The above is the custom filter , my idea is there is two filter option "bookMark" / "select all", that means select all show original list while the bookMark show bookmark item only.
The problem is , if I click on bookmark , then I click on select all , the result is still the bookmark item.
So I log the result, I found that in the second time the mUnfilteredList = (ArrayList<Spot>) items;
will rerun so the unfiltered list is only the last filter result instead of keeping the original list. How can I change to fix the problem?
Thanks for helping
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow