【发布时间】:2012-01-03 05:57:57
【问题描述】:
我有一些适用于我的 Android 应用的联系人自动完成和自动搜索算法。 首先是一些 xml 来定义输入的文本视图:
<AutoCompleteTextView
a:id="@+id/recipientBody"
a:layout_width="0dip"
a:layout_height="wrap_content"
a:layout_weight="1.0"
a:nextFocusRight="@+id/smsRecipientButton"
a:hint="@string/sms_to_whom"
a:maxLines="10"
/>
现在我设置了文本视图
AutoCompleteTextView recip =
(AutoCompleteTextView) findViewById(R.id.recipientBody);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, R.layout.list_item, getAllContacts());
recip.setAdapter(adapter);
现在是搜索与输入匹配的联系人的实际算法:
private List<String> getAllContacts() {
List<String> contacts = new ArrayList<String>();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactId}, null);
while (pCursor.moveToNext()) {
String phoneNumber = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(phoneNumber + " ( " + displayName + " )");
}
pCursor.close();
}
}
}
return contacts;
}
这适用于联系人号码和姓名输入。但是还有一个问题。用户可以输入多个电话号码。但是当一个联系人被应用到文本视图时,它不能再次搜索,因为算法需要整个字符串。
我该如何解决?
【问题讨论】: