2013-05-21 45 views
1

我希望有一個自動完成的文本框,它提供了用戶的聯繫人名稱。我的代碼如下。自定義自動完成適配器Android

private void getContactNames() 
{ 
    Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null); 
    _contactAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line); 

    while (cursor.moveToNext()) 
    { 
     int nameIdx = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME); 
     String tmp = cursor.getString(nameIdx); 
     _contactAdapter.add(tmp); 

    } 
} 

設置適配器:

AutoCompleteTextView contactName = (AutoCompleteTextView) findViewById(R.id.contactName); 
    contactName.setAdapter(_contactAdapter); 

當我這樣做時,適配器在那裏(238個通訊錄)中的所有聯繫人姓名。但是,當我開始在文本框中輸入時,自動完成不顯示。

好笑的是,當我測試它這樣做:

String[] ab = new String[] {"aaaaa", "bbbbb"}; 
     _contactAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,ab); 

到文本框中鍵入時,它會顯示「AAAAA」和「BBBBB」。

任何想法?

感謝,

湯姆

* 編輯

只是想我會跟進。它似乎是阻止它出現的絕對數量的聯繫人。任何方式來解決這個問題?

+0

工作。這就是爲什麼它不顯示你。如果你想直接從手機數據庫中搜索,然後使用。 http://developer.android.com/guide/topics/search/search-dialog.html –

回答

1
while (cursor.moveToNext()) 
{ 
    int nameIdx = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME); 
    String tmp = cursor.getString(nameIdx); 
    //_contactAdapter.add(tmp); 

    // get all names in a new arraylist and then assign it to 
     arrayList.add(tmp); 
} 

,然後當你已經的用戶列表之前將其設置爲自動完成分配給您的適配器

_contactAdapter = new ArrayAdapter<String> this,android.R.layout.simple_dropdown_item_1line, arrayList); 
+0

嗨,我感謝您的回覆,但唉,它沒有奏效。這些字符串位於適配器的「mObjects」成員中,但在開始輸入框中時不會顯示。是否因爲琴絃太長?或者我有太多元素(238)。歡呼 – Tmarsh2

+0

嘗試設置閾值,然後contactName.setThreshold(1); 和String是類的類型,所以它不用擔心你的字符串很容易適合的限制 – aditya