使用数组适配器对listview排序

amp*_*amp 28 sorting android listview

我有一个listview连接到自定义数组适配器.此列表显示TCP连接收到的更改dataSet的信息...

我能够对listview进行排序sort (Comparator<? super T> comparator),但是当dataSet被更改时,listview不再排序......

我可以在sort ()每次更改dataSet时使用,但我认为这不是最佳选择...

我怎样才能做到这一点?有什么建议?

编辑

我在实施所提出的解决方案时遇到问题......

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

我的customArrayAdapter.java的片段

    @Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
}


//-----------Order the content of the arrayAdapter------------//
public void sort(byte sortType) {

    super.sort(new MyComparatorB(sortType));
    notifyDataSetChanged();
}
Run Code Online (Sandbox Code Playgroud)

在我的MyActivity.java中

myDevAdapter.sort(SortType.ALPHA);
Run Code Online (Sandbox Code Playgroud)

当我调试时,super.sort(new MyComparatorB(sortType));调用该方法并调用MyComparatorB的构造函数.但是这个方法compare(DeviceB lhs, DeviceB rhs)永远不会调用,我的arrayList没有排序......我做错了什么?

waq*_*lam 43

我想你需要在你的适配器中覆盖notifyDataSetChanged方法,并在调用它的super之前执行排序.见下文:

@Override
public void notifyDataSetChanged() {
    //do your sorting here

    super.notifyDataSetChanged();
}
Run Code Online (Sandbox Code Playgroud)

这样做会在您调用notifyDataSetChanged方法刷新列表项时对列表进行排序.否则,将已排序的List /数组提供给适配器.


或者更优选地,使用sort适配器中可用的方法来完成工作.

adapter.sort(new Comparator<String>() {
    @Override
    public int compare(String lhs, String rhs) {
        return lhs.compareTo(rhs);   //or whatever your sorting algorithm
    }
});
Run Code Online (Sandbox Code Playgroud)

  • .sort函数自动调用notifyDataSetChanged,因此如果您使用内置排序的此代码,您将进入无限循环并溢出堆栈.只有在您自己管理列表时才这样做,但大多数使用阵列适配器的人都没有这样做. (21认同)