gpt4 book ai didi

java - 如何为 customAdapter android 实现 getFilter

转载 作者:行者123 更新时间:2023-11-29 08:53:57 26 4
gpt4 key购买 nike

我已经为自定义适配器实现了搜索功能,但仍然无法正常工作,如果有任何错误请纠正我,我已经发布了我的代码。

java代码

@Override
public Filter getFilter() {
/**
* A filter object which will filter message key
* */

return filter;
}

Filter filter = new Filter() {

@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {

mEventUtil = (List<Event>) results.values;

notifyDataSetChanged();
}

@Override
protected FilterResults performFiltering(CharSequence constraint) {

FilterResults results = new FilterResults();



if (mOriginalValues == null) {
mOriginalValues = new ArrayList<Event>(mEventUtil); // mOriginalValues

}

// if (mListItem == null) {
// mListItem = new ArrayList<String>();
// for (Event message : mOriginalValues) {
// mListItem.add(message.getEvent_Title());
// }
// }

/**
*
* If constraint(CharSequence that is received) is null returns
* the mOriginalValues(Original) values else does the Filtering
* and returns FilteredArrList(Filtered)
*
**/

if (constraint == null || constraint.length() == 0) {

/*
* CONTRACT FOR IMPLEMENTING FILTER : set the Original
* values to result which will be returned for publishing
*/
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
/* Do the filtering */
constraint = constraint.toString().toLowerCase();
List<Event> FilteredArrList = new ArrayList<Event>(mOriginalValues.size());
for (int i = 0; i < mOriginalValues.size(); i++) {
Event event = mOriginalValues.get(i);

if (event.getEvent_Title().toLowerCase().contains(constraint.toString())) {
FilteredArrList.add(event);
}else{

}
}

// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};

最佳答案

这是我最常用的实现:

@Override
public Filter getFilter() {
if (ownfilter == null)
ownfilter = new CustomFilter();

return ownfilter;
}

基本上,ownfilterCustomFilter 类的实例,它是Filter 类的扩展。在该 Filter 扩展中,您必须重写以下方法:

  • protected FilterResults performFiltering(CharSequence):您可以在此处定义如何对传递给方法的 CharSequence 执行过滤。您必须返回一个 FilterResults 对象,您必须为其设置两个字段:values,即过滤器匹配项的 List,和 count,它基本上是匹配器 (List.size()) 的数量。

  • protected void publishResults(CharSequence, FilterResults):您将从 performFiltering 传递 FilterResults,并且您所要做的就是在 count > 0 时调用 notifyDataSetChanged(),否则调用 notifyDataSetInvalidated()

就是这样。

关于java - 如何为 customAdapter android 实现 getFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21325355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com