使用数组适配器对列表视图进行排序 [英] Sort listview with array adapter
问题描述
我有一个连接到自定义阵列适配器的列表视图.此列表显示更改数据集的 TCP 连接接收的信息...
I have a listview connected to a custom array adapter. This list shows information received by a TCP connection which changes the dataSet...
我可以使用 sort (Comparator<? super T> Comparator)
对 listview 进行排序,但是当 dataSet 更改时,listview 不再排序...
I am able to sort the listview with sort (Comparator<? super T> comparator)
, but when the dataSet is changed, the listview is no more sorted...
我可以在每次更改dataSet时使用sort()
,但我认为这不是最好的选择...
I can use sort ()
every time the dataSet is changed, but I think this is not the best option...
我该怎么做?有什么建议吗?
How can I do that? Any suggestions?
编辑
我在实施所提供的解决方案时遇到问题...
I am having problems in implementing the solutions presented...
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 的片段
@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 没有排序......我做错了什么?
When I am debugging, the method super.sort(new MyComparatorB(sortType));
is called and the constructor of MyComparatorB is called too. But the method compare(DeviceB lhs, DeviceB rhs)
is never called and my arrayList is not sorted...
What I am doing wrong?
推荐答案
我猜你需要在你的适配器中重写 notifyDataSetChanged 方法并在调用它的 super 之前执行排序.见下文:
I guess you need to override notifyDataSetChanged method in your adapter and perform sorting right before calling its super. See below:
@Override
public void notifyDataSetChanged() {
//do your sorting here
super.notifyDataSetChanged();
}
这样做会在您调用 notifyDataSetChanged
方法刷新列表项时对列表进行排序.否则,将已排序的列表/数组提供给您的适配器.
Doing so will sort the list whenever you call notifyDataSetChanged
method to refresh list items. Otherwise, feed a sorted List/array to your adapter.
或者更优选地,使用 sort
方法在您的适配器中可用以完成工作.
Or more preferably, use the sort
method available in your adapter to get the job done.
adapter.sort(new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs); //or whatever your sorting algorithm
}
});
这篇关于使用数组适配器对列表视图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!