我已经根据本教程创建了一个 ListView :
http://www.vogella.com/articles/AndroidListView/article.html
在那个链接中,我已经实现了
13>在ListView中选择多个项目
我的 ListView 工作正常。我通过使用以下代码用电话联系人填充它来自定义 ListView :
private List<Model> getModel()
{
List<Model> list = new ArrayList<Model>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// This inner cursor is for contacts that have multiple numbers.
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
while (pCur.moveToNext())
{
list.add(get(name));
}
pCur.close();
}
}
}
cur.close();
return list;
}
现在会显示联系人的姓名,但不会对其进行排序。我该如何排序?
求助! 提前致谢!
最佳答案
让我们看看这个声明。
List<Model> list = new ArrayList<Model>();
这是一个 ArrayList
对象,参数化为 Model
类型。现在,在您创建的 Model
类中,您可以简单地使用 Comparable
接口(interface)。为此,您添加:
implements Comparable<Model>
到您的 Model
类 header 的末尾。
然后您将被迫为名为compareTo
的方法添加实现。这就是您比较事物的方式。
添加此实现后,您可以调用 Collections.sort()
,并将 ArrayList
对象 list 传递给它。这将为您对列表进行排序。
我觉得再深入一点
因此,首先要做的是转到您的 Model
类,该类目前有一个如下所示的标题:
public class Model
你想要做的,就是把它改成这样:
public class Model implements Comparable<Model>
这是什么意思?
那么这意味着您已同意为Comparable
接口(interface)提供代码。您现在需要在您的 Model
类中编写一个方法 compareTo
。像这样的东西:
@Override
public int compareTo(Object arg0) {
// At this point, you put your comparison code in.
}
你的对比码
如果您想按字母顺序对它们进行排序,可以使用 String
对象中的 compareTo
方法。首先,您需要将 arg0
转换为您可以使用的 String
对象:
String otherName = ((Member)arg0).getName();
然后您可以简单地返回 String compareTo
方法的值:
return otherName.compareTo(this.name);
关于java - 如何在 ListView 中对电话联系人进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16262764/