Android 使用比较器排序的ListView
这在onCreate方法中:Android 使用比较器排序的ListView,android,listview,comparator,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(); list=dba.getAllF
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();
list=dba.getAllFriends();
适配器=新阵列适配器(此,
android.R.layout.simple_list_item_1,list);
adapter.sort(Friend.NAME\u COMPARATOR);
setListAdapter(适配器);
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());
}
};
publicstaticfinalcomparatorname\u Comparator=newcomparator(){
公共整数比较(最终好友1,最终好友2){
返回friend1.getName().compareTo(friend2.getName());
}
};
知道它为什么不起作用吗
编辑:
list=dba.getAllFriends();
Collections.sort(list,Friend.NAME\u COMPARATOR);
Log.d(“listsorded”,list.toString());
适配器=新阵列适配器(此,
android.R.layout.simple_list_item_1,list);
setListAdapter(适配器);
adapter.notifyDataSetChanged();
我也像这样尝试过,得到了排序输出(LogCat),但在ListView中它保持未排序状态。Wtf?使用
就你而言:
Collections.sort(yourFriendsList,Friend.NAME_COMPARATOR);
或者最好使用适配器中可用的方法来完成
adapter.sort(new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs); //or whatever your sorting algorithm
}
});
adapter.sort(新的比较器(){
@凌驾
公共整数比较(字符串lhs、字符串rhs){
返回lhs.compareTo(rhs);//或任何排序算法
}
});
祝你好运 问题出在我的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\u COMPARATOR);
适配器=新阵列适配器(MainActivity.this,
android.R.layout.simple_list_item_1,list);
低压设置适配器(适配器);
lv.invalidate();
}
第二个选项与我的有什么不同?唯一的区别是我在另一个类中通过静态变量访问它。还是我错了?谢谢。@Ondrej'zatokar'Tokár我可以找朋友班吗?
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();
}