【问题标题】:ListView sorted, using comparatorListView 排序,使用比较器
【发布时间】:2014-03-22 13:39:58
【问题描述】:

这是在 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 中它保持未排序。怎么回事?

【问题讨论】:

    标签: android listview comparator


    【解决方案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
        }
    });
    

    祝你好运!

    【讨论】:

    • 第二个选项和我的有什么不同?唯一的区别是我在另一个类中通过静态变量访问它。还是我错了?谢谢。
    • @Ondrej'zatokar'Tokár 我可以找朋友班吗?
    【解决方案2】:

    问题出在我的 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-08
      • 1970-01-01
      • 2017-04-29
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      相关资源
      最近更新 更多