0
在該活動中,我獲取的所有聯繫人,並在listView
顯示,有一個EditText
搜索聯繫人一樣,如果我寫「妮」,那麼listView
將顯示所有以「ni」開頭的聯繫人。爲此,我使用adapter.clear()
和adapter.addAll(matchedContacts
,所有聯繫人都以「ni」開頭)。但這裏的問題是,adapter.clear()
的每一個電話正在清除contactList
(其中我已經存儲所有聯繫人)並填寫matchedContacts
的主要聯繫人列表,因爲如果我更改EditText
listView
未填充新聯繫人。爲什麼adapter.clear()清除這兩個適配器和ArrayList
下面是代碼:
public class AddPerson2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addperson2);
EditText searchContact = (EditText)findViewById(R.id.contact_search);
final ListView listView = (ListView)findViewById(R.id.contact_list);
final ArrayList<String[]> contactList = new ArrayList<>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
, ContactsContract.CommonDataKinds.Phone.NUMBER}
, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null){
if (cursor.getCount() > 0){
while (cursor.moveToNext()){
String[] contact = new String[2];
contact[0] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
contact[1] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(contact);
}
}
}
final ContactListAdapter contactListAdapter = new ContactListAdapter(this, contactList);
listView.setAdapter(contactListAdapter);
searchContact.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String startingCharacter = s.toString().toLowerCase();
ArrayList<String[]> matchedContacts = new ArrayList<>();
for (String[] contact : contactList) {
if (contact[0].toLowerCase().startsWith(startingCharacter)){
matchedContacts.add(contact);
}
}
contactListAdapter.clear();
contactListAdapter.addAll(matchedContacts);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(getResources().getColor(R.color.personSelectBackground));
Log.wtf("showid", id+"");
}
});
}
}
使用getFilter()。filter(startingCharacter)將listView留空。 –