【发布时间】:2018-09-10 13:28:01
【问题描述】:
我在RecyclerView.Adapter<> 中实现了Filterable,以按名称或地区搜索特定位置。我在Filter 中的performFiltering() 方法中记录每次迭代的结果,就像filteredLocationList 是一个类变量:
private class LocationsAdapter extends RecyclerView.Adapter<LocationsAdapter.MyViewHolder> implements Filterable {
private List<Location> locationList;
private List<Location> filteredLocationList;
LocationsAdapter(List<Location> locationList) {
this.locationList = locationList;
this.filteredLocationList = locationList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_location_row, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Location location = locationList.get(position);
holder.name.setText(location.locName);
holder.district.setText(location.locDistrict);
}
@Override
public int getItemCount() {
return filteredLocationList.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String searchTerm = constraint.toString().toLowerCase();
Log.w(TAG, "search " + searchTerm);
if (searchTerm.isEmpty()) {
filteredLocationList = locationList;
} else {
List<Location> filteredList = new ArrayList<>();
for (Location location : locationList) {
if (location.locName.toLowerCase().contains(searchTerm)) {
Log.i("location search", location.locName);
filteredList.add(location);
}
}
filteredLocationList = filteredList;
}
FilterResults searchResults = new FilterResults();
searchResults.values = filteredLocationList;
return searchResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredLocationList = (ArrayList<Location>) results.values;
notifyDataSetChanged();
}
};
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name, district;
MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
district = view.findViewById(R.id.district);
}
}
}
日志语句显示正在找到位置,但列表没有相应更新。这可能是什么原因。
【问题讨论】:
-
您的
Adapter是从filteredLocationList还是locationList中提取数据?请发布完整的课程。 -
两个列表都是类变量。我保留 locationList 以防搜索没有返回结果。
-
添加了适配器类@MikeM。
-
在
onBindViewHolder()中,您从locationList提取数据,而不是filteredLocationList。您在getItemCount()中已经正确,但即使列表的大小可能会发生变化,所列项目的实际数据也不会发生变化。
标签: android android-recyclerview android-filterable