【发布时间】:2011-11-20 20:16:25
【问题描述】:
我在 android 列表视图中使用适配器绑定类对象列表,列表视图有 3 个列标题(3 个标题按钮),每个标题都有点击事件,现在我想在我点击时按列对列表视图进行排序第一个标题列,相对于第一列排序的数据,我单击第二个标题对第二列的数据进行排序。我该怎么做。
【问题讨论】:
-
请任何人回答这个问题
标签: android sorting android-listview
我在 android 列表视图中使用适配器绑定类对象列表,列表视图有 3 个列标题(3 个标题按钮),每个标题都有点击事件,现在我想在我点击时按列对列表视图进行排序第一个标题列,相对于第一列排序的数据,我单击第二个标题对第二列的数据进行排序。我该怎么做。
【问题讨论】:
标签: android sorting android-listview
前面有大量伪代码,你已经被警告了。
假设你有一个类 Foo
class Foo{
private int param1;
private float param2;
private String param3;
}
现在制作 3 个比较器,每个要排序的成员一个。最好让它成为同一个类的静态成员。
class Foo
{
public static Comparator PARAM1_COMPARATOR = <defination>;
public static Comparator PARAM2_COMPARATOR = <defination>;
public static Comparator PARAM3_COMPARATOR = <defination>;
}
在你的活动中,有这个函数refreshList()(或类似的东西),当排序顺序被改变时被调用。
void refreshList()
{
List<Foo> list = //say this is your list
//Pro tip: User a switch case instead.
if(Sort_by_param1)
Collections.sort(list, Foo.PARAM1_COMPARATOR);
if(Sort_by_param2)
Collections.sort(list, Foo.PARAM2_COMPARATOR);
if(Sort_by_param3)
Collections.sort(list, Foo.PARAM3_COMPARATOR);
adapter.notifyDatasetChanged() or call setAdapter again with the new list.
}
【讨论】:
按照此代码对任何 ArrayList 进行排序
Collections.sort(empList, new Comparator<Employee>(){
public int compare(Employee emp1, Employee emp2) {
return emp1.getFirstName().compareToIgnoreCase(emp2.getFirstName());
}
});
【讨论】: