In my application I have create a custom list view and I want to implement a filter so that the list can be filtered according to the text entered in the EditText. I am usin
In your BaseAdapter, store two copies of the list, one original, and one filtered. And change all references in your BaseAdapter, to only use the filtered list.
1) in your activity, activate the filter on your ListView: lv.setTextFilterEnabled(true);
2) in your textWatcher, trigger the filter on your listadapter srchadptr.getFilter().filter(s)
3) Update your baseadapter to store two copies of the data, and change references to refer to the filtered list instead of the original list.
public class SearchAdapter extends BaseAdapter implements Filterable {
List list = new ArrayList();
List listFiltered = new ArrayList();
public SearchAdapter(Context context, ArrayList list) {
this.context = context;
this.inflater = LayoutInflater.from(context)
this.list = list;
this.listFiltered=list;
}
public int getCount() {
return listFiltered.size();//note the change
}
public Object getItem(int position) {
return listFiltered.get(position);//note the change
}
//only altered lines shown in this function (change ``list`` to ``listFiltered``)
public View getView(final int position, View convertView, ViewGroup parent) {
tv.setText(String.valueOf(listFiltered.get(position)));
btn.setText(String.valueOf(listFiltered.get(position)));
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, listFiltered.get(position), Toast.LENGTH_LONG).show();
}
});
}
//now write your filter function
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
//no constraint given, just return all the data. (no search)
results.count = list.size();
results.values = list;
} else {//do the search
List resultsData = new ArrayList<>();
String searchStr = constraint.toString().toUpperCase();
for (String s : list)
if (s.toUpperCase().contains(searchStr)) resultsData.add(s);
results.count = resultsData.size();
results.values = resultsData;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
listFiltered = (ArrayList) results.values;
notifyDataSetChanged();
}
};
}