按降序和升序排序电话联系人

时间:2018-03-22 07:41:47

标签: android sorting contacts

我正在列表视图中加载手机的联系人,我按升序排序。

现在我有2个按钮: Ascending Descending 。如何更改列表视图以根据单击的按钮以升序和降序显示联系人?

1 个答案:

答案 0 :(得分:0)

尝试升序,

    ArrayList<Contact> contactArrayList=new ArrayList<>();
    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    while (phones.moveToNext()) {
        //get the data of each contact and store in list (here the item is Contact object)
        //for example
        Contact contact=new Contact();
        contact.setName("//get name of contact");
        contact.setPhonenumber("//get phonenum of contact");
        contactArrayList.add(contact);


    }
    phones.close();
    Collections.sort(contactArrayList, new Comparator<Contact>() {
        @Override
        public int compare(Contact lhs, Contact rhs) {
            //get the item which is to be compared
            //here I have used name(String) of the contacts
            String lhsString = lhs.getName();
            String rhsString = rhs.getName();
            return lhsString.compareToIgnoreCase(rhsString);
        }
    });

降序,

return rhsString.compareToIgnoreCase(lhsString);