It seems that the use case for an Adapter
that is Filterable
is to filter by a String
or CharSequence
that might be entered by the user in an EditText
, but is this really the only criteria the platform offers for filtering Adapter
s?
What if I have a backing data structure of objects that can be otherwise categorized? for example, what if I have a list of Shirt objects that have an enum
attribute, color
? The user should be able to filter the list of shirts from a list of available color
s. As a good application developer I want to use the platforms built in filtering mechanism, but all I can find is this Filter
with methods like filter (CharSequence constraint)
. I must be missing something. I see how it would be simple enough to implement this filtering mechanism inside my own custom BaseAdapter
, but it feels like there should be some built in way to do custom filters. Anyone? Thanks in advance.
In Android, your adapter can implement the Filterable (that may be same with Filter you searched)
=> This is the connection between your data with the Filter.
Here is the link
[You should see the marked answer] List View Filter Android
you can create your own FilterAdapter and bring your own logics, for example this one take care of object with two strings and manage the filter:
public class TwoWordsFilter extends Filter {
ArrayList<BranchData> branchDatas = new ArrayList<BranchData>();
private BranchDataAdapter branchDataAdapter;
public TwoWordsFilter(ArrayList<BranchData> branchDatas,BranchDataAdapter branchDataAdapter) {
this.branchDatas = branchDatas;
this.branchDataAdapter=branchDataAdapter;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint==null || constraint.length()==0){
results.values=branchDatas;
results.count=branchDatas.size();
}else {
List<BranchData> mBranchDatas=new ArrayList<BranchData>();
for (BranchData branchData : branchDatas) {
if (branchData.getBranch_name().trim().toLowerCase().startsWith(constraint.toString().trim().toLowerCase()) ||
branchData.getCity().trim().toLowerCase().startsWith(constraint.toString().trim().toLowerCase())){
mBranchDatas.add(branchData);
}
}
results.values=mBranchDatas;
results.count=mBranchDatas.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0)
branchDataAdapter.notifyDataSetInvalidated();
else {
branchDataAdapter.setBranchDatas((ArrayList<BranchData>) results.values);
branchDataAdapter.notifyDataSetChanged();
}
}
}
in your adapter put this:
@Override
public Filter getFilter() {
if (twoWordsFilter==null){
twoWordsFilter=new TwoWordsFilter(branchDatas,this);
}
return twoWordsFilter;
}
Check PickerFragment.GraphObjectFilter for more details - mach 2013-03-20 10:26