我有一个连接到自定义数组适配器的 ListView 。此列表显示 TCP 连接接收到的更改数据集的信息...
我可以使用 sort (Comparator<? super T> comparator)
对 ListView 进行排序,但是当dataSet发生变化时,listview就不再排序了……
我可以使用 sort ()
每次更改数据集,但我认为这不是最好的选择...
我该怎么做?有什么建议吗?
编辑
我在实现所提供的解决方案时遇到问题...
MyComparatorB.java
public class MyComparatorB implements Comparator<DeviceB> {
private byte orderType;
public MyComparatorB(byte type) {
this.orderType = type;
}
public int compare(DeviceB lhs, DeviceB rhs) {
int res = 0;
if (orderType == SortType.ALPHA) {
res = (lhs.getName()).compareTo(rhs.getName());
}
else if (orderType == SortType.LAST_ACT) {
res = (rhs.getTime().getTime()).compareTo(lhs.getTime().getTime());
}
return res;
}
}
我的 customArrayAdapter.java 的 fragment
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
//-----------Order the content of the arrayAdapter------------//
public void sort(byte sortType) {
super.sort(new MyComparatorB(sortType));
notifyDataSetChanged();
}
在我的 MyActivity.java 中
myDevAdapter.sort(SortType.ALPHA);
我在调试的时候,方法super.sort(new MyComparatorB(sortType));
被调用并且 MyComparatorB 的构造函数也被调用。但是方法compare(DeviceB lhs, DeviceB rhs)
永远不会被调用,并且我的 arrayList 没有排序......
我做错了什么?
最佳答案
我猜你需要重写适配器中的 notifyDataSetChanged 方法并在调用它的 super 之前执行排序。见下文:
@Override
public void notifyDataSetChanged() {
//do your sorting here
super.notifyDataSetChanged();
}
这样做会在您调用 notifyDataSetChanged
方法刷新列表项时对列表进行排序。否则,将排序的列表/数组提供给您的适配器。
或者更优选地,使用sort
适配器中可用的方法来完成工作。
adapter.sort(new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs); //or whatever your sorting algorithm
}
});
关于android - 使用数组适配器对 ListView 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9906464/