问题描述
我刚接触Android.我想为ListView实现预定义的过滤器.我的ListView将包含数字,并且会有一个过滤器图标,单击该图标应显示显示奇数",显示偶数"和显示全部"之类的选项.
I am pretty new to Android. I want to implement predefined filters for a ListView. My ListView will contain numbers and there would be a Filter icon which on click should show options like "Show odd", "Show even" and "Show all".
我的问题是如何在单击过滤器"图标时显示弹出对话框?如果使用一个简单的弹出对话框实现了此目的,那么如何使用选定的选项过滤ListView?我尝试搜索Android论坛,但他们主要谈论的是文本过滤器.指向具有类似问题陈述的文章的指针也可能会有所帮助.
My question is how to display a popup dialog on click of the Filter icon? If that is achieved using a simple popup dialog, then how do I filter the ListView with the option selected? I tried searching Android forums but they speak mainly about text filters. Pointers to articles having similar problem statement could also help.
推荐答案
您可以实现过滤器是这样的:
class MyFilter extends Filter {
private final MyAdapter myAdapter;
public MyFilter(MyAdapter myAdapter) {
this.myAdapter = myAdapter;
}
@Override
protected Filter.FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
// unfiltered: show all
results.values = myAdapter.getOriginalList();
results.count = myAdapter.getOriginalList().size();
} else {
// filtered
List<Integer> newWorkingList = new ArrayList<>();
if (constraint.equals('1')) {
// odd
for (Integer integer : myAdapter.getOriginalList()) {
if (integer % 2 == 1) {
newWorkingList.add(integer);
}
}
} else if (constraint.equals('2')) {
// even
for (Integer integer : myAdapter.getOriginalList()) {
if (integer % 2 == 0) {
newWorkingList.add(integer);
}
}
}
results.values = newWorkingList;
results.count = newWorkingList.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
myAdapter.setFilteredList((List<String>) results.values);
if (results.count == 0) {
myAdapter.notifyDataSetInvalidated();
} else {
myAdapter.notifyDataSetChanged();
}
}
}
在适配器类中,您必须进行以下更改:
In your adapter class you have to make changes similar to these:
public class MyAdapter extends ArrayAdapter<Integer> implements Filterable
private MyFilter MyFilter;
@Override
public Filter getFilter() {
if (myFilter == null) {
myFilter = new myFilter(this);
}
return myFilter;
}
并且您必须为原始列表添加一个setter.
And you have to add a setter for your original list.
最后,在弹出对话框的侦听器中,您必须根据用户的选择添加以下行:
And, finally, in the listener of your popup dialog you have to add these lines depending on the user's choice:
myAdapter.getFilter().filter(null);
myAdapter.getFilter().filter('1');
myAdapter.getFilter().filter('2');
这篇关于使用预定义的过滤器过滤android ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!