如何操作列表视图,以便始终在顶部显示特定的电话号码?

时间:2017-08-12 22:03:14

标签: android listview adapter

如何将手机通讯录中的电话号码3456781276显示在listview的最顶部,然后是正常情况下的所有其他联系人?我相信我将这个值传递到我的自定义适配器和我的getView(),但根本不知道如何继续。你能帮忙吗?

在我的ListView中,我使用以下代码显示所有手机通讯录:

  class LoadContact extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... voids) {


//          we want to delete the old selectContacts from the listview when the Activity loads
//          because it may need to be updated and we want the user to see the updated listview,
//          like if the user adds new names and numbers to their phone contacts.
            selectPhoneContacts.clear();

//          we have this here to avoid cursor errors
            if (cursor != null) {
                cursor.moveToFirst();

            }


            try {

//                get a handle on the Content Resolver, so we can query the provider,
                cursor = getApplicationContext().getContentResolver()
//                the table to query
                 .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                null,
                                null,
//               display in ascending order
                 ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");

//                get the column number of the Contact_ID column, make it an integer.
//                I think having it stored as a number makes for faster operations later on.
//                get the column number of the DISPLAY_NAME column
                int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
//                 get the column number of the NUMBER column
                int phoneNumberofContactIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

                cursor.moveToFirst();

//              We make a new Hashset to hold all our contact_ids, including duplicates, if they come up
                Set<String> ids = new HashSet<>();

                do {

                    System.out.println("=====>in while");

//                        get a handle on the display name, which is a string
                    name = cursor.getString(nameIdx);

//                        get a handle on the phone number, which is a string
                    phoneNumberofContact = cursor.getString(phoneNumberofContactIdx);


                    //----------------------------------------------------------


                    // get a handle on the phone number of contact, which is a string. Loop through all the phone numbers
//                  if our Hashset doesn't already contain the phone number string,
//                    then add it to the hashset
                    if (!ids.contains(phoneNumberofContact)) {
                        ids.add(phoneNumberofContact);

                        System.out.println(" Name--->" + name);
                        System.out.println(" Phone number of contact--->" + phoneNumberofContact);

                                SelectPhoneContact selectContact = new SelectPhoneContact();

                                selectContact.setName(name);
                                selectContact.setPhone(phoneNumberofContact);
                                selectPhoneContacts.add(selectContact);
                    }

                } while (cursor.moveToNext());


            } catch (Exception e) {
                Toast.makeText(NewContact.this, "what the...", Toast.LENGTH_LONG).show();
                e.printStackTrace();
                //   cursor.close();
            } finally {

            }


    if (cursor != null) {
        cursor.close();

    }
    return null;
}


        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            adapter = new SelectPhoneContactAdapter(selectPhoneContacts, NewContact.this);

//                    we need to notify the listview that changes may have been made on
//                    the background thread, doInBackground, like adding or deleting contacts,
//                    and these changes need to be reflected visibly in the listview. It works
//                    in conjunction with selectContacts.clear()
            adapter.notifyDataSetChanged();

            listView.setAdapter(adapter);

            //this function measures the height of the listview, with all the contacts, and loads it to be that
            //size. We need to do this because there's a problem with a listview in a scrollview.
            justifyListViewHeightBasedOnChildren(listView);

        }
    }

我的模特,吸气鬼和制定者,就像:

public class SelectPhoneContact {

    String phone;

    public String getPhone() {return phone;}

    public void setPhone(String phone) {
        this.phone = phone;
    }

    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

我的自定义适配器:

 public class SelectPhoneContactAdapter extends BaseAdapter {

    //define a list made out of SelectContacts and call it theContactsList
    public List<SelectPhoneContact> theContactsList;
    //define an array list made out of SelectContacts and call it arraylist
    private ArrayList<SelectPhoneContact> arraylist;
    Context _c;

    //define a ViewHolder to hold our name and number info, instead of constantly querying
    // findviewbyid. Makes the ListView run smoother
    ViewHolder v;

    public SelectPhoneContactAdapter(List<SelectPhoneContact> selectPhoneContacts, Context context) {
        theContactsList = selectPhoneContacts;
        _c = context;
        this.arraylist = new ArrayList<SelectPhoneContact>();
        this.arraylist.addAll(theContactsList);


        Collections.sort(this.arraylist, new Comparator<SelectPhoneContact>() {
                @Override
                public int compare(SelectPhoneContact t1, SelectPhoneContact t2) {
                    if(t2.getPhone().equals ("3456781276")) {   // put the phone number you want on top here
                        return 1;
                    } else {
                        return t1.getName().compareTo(t2.getName());
                    }
                }


            });

        }



    @Override
    public int getCount() {
        return arraylist.size();
    }

    @Override
    public Object getItem(int i) {
        return arraylist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)

    static class ViewHolder {
        //        In each cell in the listview show the items you want to have
//        Having a ViewHolder caches our ids, instead of having to call and load each one again and again
        CheckBox checkbox;
        TextView title, phone, lookup;
//        CheckBox check;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {

        //we're naming our convertView as view
        View view = convertView;

        if (view == null) {

            //if there is nothing there (if it's null) inflate the layout for each row
            LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = li.inflate(R.layout.phone_inflate_listview, null);

            //or else use the view (what we can see in each row) that is already there
        } else {
            view = convertView;
        }

        v = new ViewHolder();

//      So, for example, title is cast to the name id, in phone_inflate_listview,
//        phone is cast to the id called no etc
        v.title = (TextView) view.findViewById(R.id.name);
//        v.check = (CheckBox) view.findViewById(R.id.check);
        v.phone = (TextView) view.findViewById(R.id.no);

//        store the holder with the view
        final SelectPhoneContact data = (SelectPhoneContact) arraylist.get(i);
        v.title.setText(data.getName());
        v.phone.setText(data.getPhone());

        view.setTag(data);

        return view;
    }

}

4 个答案:

答案 0 :(得分:2)

尝试修改适配器的构造函数,如下所示:

public SelectPhoneContactAdapter(List<SelectPhoneContact> selectPhoneContacts, Context context) {
    theContactsList = selectPhoneContacts;
    _c = context;
    this.arraylist = new ArrayList<SelectPhoneContact>();
    this.arraylist.addAll(theContactsList);

    Collections.sort(this.arraylist, new Comparator<SelectPhoneContact>() {
        @Override
        public int compare(SelectPhoneContact t1, SelectPhoneContact t2) {
            if(t2.getPhone().equals("3456781276")) {   // put the phone number you want on top here
                return 1;
            } else {
                return t1.getName().compareTo(t2.getName());
            }
        }
    });
}

因此我们基本上在适配器开始使用它之前对ArrayList进行排序。

所以在这个例子中,我正在拨打电话号码&#34; 3456781276&#34;在其他一切之上。如果电话号码不是&#34; 3456781276&#34;,它将按名称对所有项目进行排序。 (如果您不想按名称对其进行排序,请删除else声明。

希望这有帮助。

修改

getView()中,更改:

final SelectPhoneContact data = (SelectPhoneContact) theContactsList.get(i);

为:

final SelectPhoneContact data = (SelectPhoneContact) arraylist.get(i);

像这样改变getCount()方法:

@Override
public int getCount() {
    return arraylist.size();
}

像这样改变getItem()方法:

@Override
public Object getItem(int i) {
    return arraylist.get(i);
}

您必须在任何地方使用arraylist,因为这是我们正在排序的列表。

答案 1 :(得分:2)

如何使用add(int index, E element)

if (/* check your condition here: is it the number you are looking for? */) {
    // insert the contact at the beginning
    selectPhoneContacts.add(0, selectContact);
} else {
    // insert it at the end (default)
    selectPhoneContacts.add(selectContact);
}

答案 2 :(得分:1)

实现此目的的简单方法是,只使用包含电话号码的XML视图,并在默认情况下将其设置为不可见,如果列表显示,则将视图设置为可见。我希望这篇文章可以帮助你!!!

答案 3 :(得分:1)

您可以通过循环浏览联系人轻松操作ArrayListCollections.swap();的项目位置,只需检查与您的号码匹配的号码,例如将其放在顶部: Collections.swap(myArrayList, i, 0);

参阅:http://www.java2s.com/Code/Java/Collections-Data-Structure/SwapelementsofJavaArrayList.htm