创建一个AutoCompleteTextView,它可以从两个可能的源自动完成

时间:2015-07-11 19:43:22

标签: android autocompletetextview

所以我制作一个简单的短信应用程序来教自己一些Android,当用户发送新邮件时,我希望用户能够键入联系人的姓名或联系人&# 39;电话号码,并且在任何一种情况下都有相同的联系方式,就像大多数短信应用程序的行为一样。

现在,我有一个工作的AutoCompleteTextView仅适用于电话号码。代码如下所示:

protected void onCreate(Bundle savedInstanceState) {
    //Set up the behavior for the recipient field.
    destination = (AutoCompleteTextView) findViewById(R.id.destination_number);

    //Get the list of contacts, add it to an array adapter.
    ArrayList<String>[] contactNames = getContactList();
    ArrayList<String> contactNumbers = getContactNumbers(contactNames[1]);

    //Initialize the ArrayAdapter.
    ArrayAdapter<String> contactAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactNumbers);
    destination.setAdapter(contactAdapter);
    destination.setThreshold(2);

    ...
/**
 * Gets a list of all contacts with phone numbers.
 * @return A list of all contact names and IDs with associated phone numbers. Index 0 contains phone numbers and index 1 contains IDs
 */
public ArrayList<String>[] getContactList(){
    ArrayList<String>[] contactList = new ArrayList[2];
    contactList[0] = new ArrayList<>();
    contactList[1] = new ArrayList<>();

    Cursor mContactsCursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, "HAS_PHONE_NUMBER = 1", null, null);
    while(mContactsCursor.moveToNext()){
        contactList[0].add(mContactsCursor.getString(mContactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
        contactList[1].add(mContactsCursor.getString(mContactsCursor.getColumnIndex(ContactsContract.Contacts._ID)));
    }

    mContactsCursor.close();

    return contactList;
}

/**
 * Gets a list of phone numbers associated with the given list of contact IDs.
 * @param id a list of contact IDs
 * @return An ArrayList containing all phone numbers associated with the contacts.
 */
public ArrayList<String> getContactNumbers(ArrayList<String> id){
    ArrayList<String> numbers = new ArrayList<>();

    //Loop through the given list of IDs, and add the phone number from each to the list of
    //Phone numbers.
    for(int i = 0; i < id.size(); i++){
        Uri contact = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id.get(i));
        Cursor contactCursor = getContentResolver().query(contact, new String[]{ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER}, null, null, null);             //TODO ensure that I'm only getting the needed columns, same with the above query.
        while (contactCursor.moveToNext()){
            String current = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
            current = current.substring(2);
            numbers.add(current);
        }
    }
    return numbers;
}

我知道我可能需要创建一个自定义的ArrayAdapter和布局,但我不了解我在ArrayAdapter中实际需要做什么才能使其工作。对不起,这是一般的,我不知道从哪里开始。

0 个答案:

没有答案