我正在尝试在listView上设置一个简单的搜索。我正在设置自定义适配器:
MainActivity.java
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView);
adapter = new AerodromesAdapter( this , aerodromes);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
aerodromes是一个ArrayList set global
ArrayList<Aerodrome> aerodromes = new ArrayList<Aerodrome>();
在我的ArrayAdapter AerodromeAdapter中,我按照以下方式实现了过滤器
AerodromeAdapter.java
ArrayList<Aerodrome> aerodromes; // Displayed list
ArrayList<Aerodrome> aerodromesInit; // Original list
private Filter filter;
private Context ctx;
public AerodromesAdapter(Context context, ArrayList<Aerodrome> aerodromes) {
super(context, R.layout.listview_item, aerodromes);
this.ctx = context;
this.aerodromes = aerodromes;
this.aerodromesInit = this.aerodromes;
}
[...]
private class AerodromeFilter extends Filter {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
Log.v("VALUES", "publishResults");
if (results.count == 0) {
notifyDataSetInvalidated();
} else {
aerodromes = (ArrayList<Aerodrome>) results.values;
Log.v("VALUES", String.valueOf(aerodromesInit.size()));
notifyDataSetChanged();
}
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new Filter.FilterResults();
// perform your search here using the searchConstraint String.
if(constraint == null || constraint.length() == 0){
results.values = aerodromesInit;
results.count = aerodromesInit.size();
}else{
ArrayList<Aerodrome> filteredList = new ArrayList<Aerodrome>();
for(Aerodrome j: aerodromesInit){
if( j.code.toLowerCase().contains(constraint.toString().toLowerCase()) || j.name.toLowerCase().contains(constraint.toString().toLowerCase()) )
filteredList.add(j);
}
results.values = filteredList;
results.count = filteredList.size();
}
Log.v("VALUES", "Recherche " + constraint.toString());
Log.v("VALUES", "Trouvés " + results.count);
return results;
}
}
在搜索栏中输入时,performFiltering工作正常并返回正确的结果,但notifyDataSetChanged();
似乎根本不起作用。
我读了很多notifyDataSetChanged();线程问题,但无法弄清楚我做错了什么。