I bind list of class objects using adapters in android list view, the list view have 3 column headers(3 header buttons), each header have click event, now i want to sort list view by column means when ever i click on first header column, the data sorted with respect to first column, i click s开发者_如何学JAVAecond header sorted the data with respect to second column.How can i do this one.
Loads of pseudo code ahead, you've been warned.
Say you have a class Foo
class Foo{
private int param1;
private float param2;
private String param3;
}
Now make 3 Comparators, one for each member you want to sort with. Preferably make it a static member of the same class.
class Foo
{
public static Comparator PARAM1_COMPARATOR = <defination>;
public static Comparator PARAM2_COMPARATOR = <defination>;
public static Comparator PARAM3_COMPARATOR = <defination>;
}
In your activity, have this function refreshList()
(or something of that sort ) which is called when the sorting order is to be changed.
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.
}
Follow this code to sort any ArrayList
Collections.sort(empList, new Comparator<Employee>(){
public int compare(Employee emp1, Employee emp2) {
return emp1.getFirstName().compareToIgnoreCase(emp2.getFirstName());
}
});
精彩评论