我有一个获取 Facebook 好友的列表视图,我想按字母顺序对名称进行排序,但我不太确定如何继续执行此操作。
这是代码:
@Override
public void onComplete(List<Profile> friends) {
// populate list
List<String> values = new ArrayList<String>();
for (Profile profile : friends) {
//profile.getInstalled();
values.add(profile.getName());
}
ArrayAdapter<String> friendsListAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_items2, values);
mFriendsList.setAdapter(friendsListAdapter);
}
};
我四处寻找解决方案,但没有找到 arraydapter。
你可以使用
ArrayAdapter.sort
friendsListAdapter.sort(new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
});
您需要创建一个比较器来为您排序。
public class MyComparator implements Comparator<Profile> {
@Override
public int compare(Profile p1, Profile p2) {
return p1.getName().compareTo(p2.getName());
}
}
那么你只需要做
Collections.sort(values, new MyComparator());
或者简单地你可以创建一个匿名类
Collections.sort(values, new Comparator<Profile>(){
public int compare(Profile p1, Profile p2) {
return p1.getName().compareTo(p2.getName());
}
});
既然你想对一个简单的字符串数组列表进行排序,就这样做
Collections.sort(values)
在将列表传递到 ArrayAdapter 之前。 当项目在 ListView 中呈现时,它应该已经显示排序结果。
*附加说明: 如果您希望对对象进行复杂的排序,您可以通过将 Comparator 的实现作为 Collections.sort() 的第二个参数传递来使用自定义排序
使用
Comparator
。您可以在其中定义要比较的内容以及如何比较,在 compare()
方法中,您可以定义应该从两个实例返回的内容。这是 String
Comparator
的示例。
new Comparator<String>() {
public int compare(final String user1, final String user2) {
// This would return the ASCII representation of the first character of each string
return (int) user2.charAt(0) - (int) user1.charAt(0);
};
};
一旦定义,您只需通过
ListView
方法将其分配给 .sort()
即可。如果您使用带有自定义 Class
的自定义布局,这就是您将收到的 compare()
参数,因此上面只是带有两个 String
的简单布局的示例。将其添加到您正在使用的布局中,它将被排序。
在 Kotlin 中你可以使用...
values.sort()