我有一些联系人自动完成和自动搜索算法适用于我的 Android 应用程序。 首先是一些 xml 来定义输入的 TextView :
<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"
/>
现在我设置 TextView
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;
}
这对于联系电话号码和姓名输入都很好。但是还有一个问题。用户可以输入多个电话号码。但是,当一个联系人应用于 TextView 时,它无法再次搜索,因为该算法会占用整个字符串。
我该如何解决?
最佳答案
编辑:
好吧,我考虑了一会儿,发现我的解决方案有问题 - 没有地方可以将完成列表中的联系人插入到 TextView 中。
解决方案似乎是MultiAutoCompleteTextView ,这个东西就是为了解决你的问题而设计的。
抱歉造成混淆!
对我来说,您似乎需要一个自定义适配器。
您可以扩展 ArrayAdapter<String>
并实现 getFilter()
- 当然,您还需要一个自定义过滤器(扩展 Filter
),您将从该方法返回哪个实例。
过滤器的 performFiltering
方法有一个参数 - 需要建议列表的字符串。您需要在最后一个逗号(或您用作分隔符的任何字符)之后获取部分并返回该子字符串的建议列表。
附言
为了更好的用户体验,您还可以考虑使用 Spans 为您的 AutoCompleteTextView 内容设置样式:http://ballardhack.wordpress.com/2011/07/25/customizing-the-android-edittext-behavior-with-spans/
关于Android TextView 自动完成和自动搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705468/