这是在onCreate方法:
list = dba.getAllFriends();
adapter = new ArrayAdapter<Friend>(this,
android.R.layout.simple_list_item_1, list);
adapter.sort(Friend.NAME_COMPARATOR);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
这是比较器:
public static final Comparator<Friend> NAME_COMPARATOR = new Comparator<Friend>() {
public int compare(final Friend friend1, final Friend friend2) {
return friend1.getName().compareTo(friend2.getName());
}
};
知道为什么它不工作吗?
编辑:list = dba.getAllFriends();
Collections.sort(list, Friend.NAME_COMPARATOR);
Log.d("ListSorted", list.toString());
adapter = new ArrayAdapter<Friend>(this,
android.R.layout.simple_list_item_1, list);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
我也尝试过这样,我得到了排序输出(LogCat),但在ListView中它保持未排序。Wtf ?
使用集合。sort(List List,Comparator c);
在你的例子中:
Collections.sort(yourFriendsList,Friend.NAME_COMPARATOR);
或者最好使用适配器中可用的sort
方法来完成。
adapter.sort(new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs); //or whatever your sorting algorithm
}
});
google好运!
问题是在我的onResume方法中,我没有用排序更新它。我不知道为什么在我的应用程序开始时它的onResume方法被调用如果你留下评论我会很高兴。顺便说一句,如果我对列表进行排序,或者我用:
排序,这两种方式都可以工作。adapter.sort(Friend.NAME_COMPARATOR);
或:
public void onResume() {
super.onResume();
ListView lv = this.getListView();
adapter.notifyDataSetChanged();
list = dba.getAllFriends();
Collections.sort(list, Friend.NAME_COMPARATOR);
adapter = new ArrayAdapter<Friend>(MainActivity.this,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.invalidate();
}