繁体   English   中英

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

[英]How do I manipulate listview so a specific phone number always appears at the top?

如何使电话联系人中的电话号码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);

        }
    }

我的模型,getter和setter,就像:

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;
    }

}

尝试像这样修改适配器的构造函数:

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进行排序。

因此,在此示例中,我将电话号码“ 3456781276”放在其他所有内容之上。 如果电话号码不是“ 3456781276”,它将按名称对所有项目进行排序。 (如果不想按名称排序,只需删除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 ,因为这是我们正在排序的列表。

使用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);
}

实现此目的的简便方法是,仅使用包含电话号码的XML视图,并将其默认设置为不可见,如果列表显示,则将视图设置为可见。 希望这篇文章对您有所帮助!!!

您可以使用Collections.swap();轻松处理ArrayList项目位置Collections.swap(); 通过遍历您的联系人并简单地检查数字是否与您的数字匹配(如果确实将其放在顶部),例如: Collections.swap(myArrayList, i, 0);

引用: http : //www.java2s.com/Code/Java/Collections-Data-Structure/SwapelementsofJavaArrayList.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM