我有谷歌一段时间,有一个listview搜索教程,
但是,对于我的情况它使用自定义对象(服务字符串,int obj)而不是列表视图中的一个字符串
http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/
所以像这样的代码不适用于我的情况:
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
我想知道如果提供的数据类似于ArrayList<CustomObj> instead of ArrayList<String>
,setFilter()是否有效,那么如何解决这个问题呢?谢谢你的帮助
答案 0 :(得分:1)
您可以通过覆盖BaseAdapter.getFilter()
方法来实现自己的过滤。
private ArrayList<CustomObj> mFilteredList, mUnfilteredList;
private Filter mFilter;
@Override
public Filter getFilter() {
if(mFilter == null) {
mFilter = new Filter() {
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mFilteredList = (ArrayList<CustomObj>)results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<CustomObj> newList = new ArrayList<CustomObj>();
for (CustomObj obj : mUnfilteredList) {
// Compare the custom object and add to list if match
if(customCompare(obj, constraint)
newList.add(obj);
}
results.values = newList;
results.count = newList.size();
return results;
}
};
}
return mFilter;
}