ListView使用比较器排序

时间:2014-03-22 13:39:58

标签: android listview comparator

这是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中它保持未排序。跆拳道?

2 个答案:

答案 0 :(得分:1)

使用Collections.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
    }
});

Goog运气好!

答案 1 :(得分:0)

问题出现在我的onResume方法中,我没有用排序更新它。确实,我不知道为什么在我的应用程序启动时它会调用onResume方法,所以如果你发表评论,我会很高兴的。 BTW两种方式都可以正常工作,如果我对列表进行排序或者我将其排序:

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();
}
相关问题