在此活动中,我正在获取所有联系人并在listView
中显示,并且有EditText
来搜索联系人,例如,如果我写了" ni"然后listView
将显示以" ni"开头的所有联系人。要这样做,我使用的是adapter.clear()
和adapter.addAll(matchedContacts
,所有联系人都会以" ni")开始每次击键。但问题在于,adapter.clear()
的每次调用都清除了contactList
的主要联系人列表(我已存储了所有联系人)并填写matchedContacts
,因为如果我更改EditText
listView
没有填充新联系人。
以下是代码:
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+"");
}
});
}
}
答案 0 :(得分:2)
如果ContactListAdapter
是ArrayAdapter
,则clear()
的行为符合预期:
clear()
上调用ArrayList
,从而将其清空notifyDataSetChanged()
上调用AdapterView
,让其了解数据中的更改也许您希望通过调用适配器上的getFilter().filter()
来对适配器进行过滤。 This sample app证明了这一点,但我使用的是SearchView
而不是EditText
。