【发布时间】:2017-12-05 04:09:56
【问题描述】:
我正在使用可过滤的搜索过滤器。当我按关键字搜索时,我设法得到搜索结果,但第一次搜索后列表视图为空。我希望它在用户输入为空时显示所有数据。
这是我编辑的代码。现在我无法获得任何搜索结果。知道哪一部分还错了吗?
public class ProductListAdapter extends BaseAdapter implements Filterable {
private Context context;
private int layout;
private ArrayList<Booth> productList= new ArrayList<>();
private ArrayList<Booth> tempList = new ArrayList<>();
private ValueFilter mFilter = new ValueFilter();
public ProductListAdapter(Context context, int layout, ArrayList<Booth> productList) {
this.context = context;
this.layout = layout;
this.productList = productList;
this.tempList = productList;
}
@Override
public int getCount() {
return tempList.size();
}
public void addItems(ArrayList<Booth> items) {
productList.addAll(items);
tempList.addAll(items);
notifyDataSetChanged();
}
@Override
public Object getItem(int position) {
return tempList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(
int position, View view, ViewGroup viewGroup) {
Typeface face_02 = Typeface.createFromAsset(context.getAssets(), "customfont/grb.otf");
ViewHolder holder = new ViewHolder();
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(layout, null);
holder.Boothname = (TextView) view.findViewById(R.id.Boothname);
holder.Rating = (TextView) view.findViewById(R.id.Rating);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Booth product = productList.get(position);
holder.Boothname.setText(product.getBoothName());
holder.Rating.setText(product.getRating());
holder.Rating.setTypeface(face_02);
holder.Boothname.setTypeface(face_02);
return view;
}
@Override
public Filter getFilter() {
return mFilter;
}
private class ValueFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Booth> filterList = new ArrayList<Booth>();
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < productList.size(); i++) {
if ((productList.get(i).getBoothName().toLowerCase())
.contains(constraint.toString().toLowerCase())) {
Booth boothdata = new Booth(productList.get(i)
.getBoothName(), productList.get(i)
.getRating());
filterList.add(boothdata);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = productList.size();
results.values = productList;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
tempList = (ArrayList<Booth>) results.values;
notifyDataSetChanged();
}
}
class ViewHolder {
TextView Boothname, Rating;
}
}
【问题讨论】:
-
您可以过滤
ListView,甚至无需与适配器交互,方法是使用临时列表并使用addTextChangedListener将原始列表中的项目排序到临时列表中以获取EditText。我在自定义 ListView 适配器上使用这种方式,效果很好。需要这个吗?分享包含ListView的 java 类。
标签: android listview filter android-filterable