android 模糊查找,并标红关键字实现

1、获取所有数据源;

2、获取关键字,并比较是否包含关键字;

3、包含时,添加到需要小时的数据中,查找完成后,通知adapter更新显示。

上代码:

1、位listview添加TextWatcher监听,在输入完成后,获取关键字。

@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
updateStates();
}


@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub


}


@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub


}

这个是在有内容时候显示删除图标,没有内容显示搜索图标

private void updateStates() {
if (mSearchInfo.length() < 1) {
mSearchInfo.setCompoundDrawablesWithIntrinsicBounds(mSearch, null, null, null);
if (mSearchContacts != null)
mSearchContacts.clear();
} else {
mSearchInfo.setCompoundDrawablesWithIntrinsicBounds(null, null, mDel, null);
mKeyWord = mSearchInfo.getText().toString();
searchContacts();
}
if (null != mSearchContacts && mSearchContacts.size() > 0) {
mSearchShow.setVisibility(View.VISIBLE);
if (mAdapter != null)
mAdapter.notifyDataSetChanged();
} else {
mSearchShow.setVisibility(View.GONE);
}
}

2、查找内容:

private void searchContacts() {
if (null != mSearchContacts)
mSearchContacts.clear();
if (null == mAllContacts || mAllContacts.size() == 0 || null == mKeyWord) {
Log.d("tiger", "no contacts or keyword is null , so return!");
return;
}
for (Object info : mAllContacts) {
if (info instanceof ContactsInfo) {
ContactsInfo contactsInfo = (ContactsInfo) info;
String name = contactsInfo.getName();
if (null != name && name.contains(mKeyWord)) {
mSearchContacts.add(contactsInfo);
continue;
}
String id = contactsInfo.getIpocid();
if (null != id && id.contains(mKeyWord)) {
mSearchContacts.add(contactsInfo);
continue;
}
}
}
}

3、通知adapter更新:

4、把关键字设置为红色:

private Object checkKeyWord(String check) {
if (null == mKeyWord)
return check;
if (check != null && check.contains(mKeyWord)) {
int index = check.indexOf(mKeyWord);
int len = mKeyWord.length();
Spanned temp = Html.fromHtml(
check.substring(0, index) + "" + check.substring(index, index + len)
+ "
" + check.substring(index + len, check.length()));


return temp;
}
return check;
}

5、判断是否含有关键字,并设值。

Object newName = checkKeyWord(name);
if (newName instanceof Spanned) {
hold.name.setText((Spanned) newName);
} else {
hold.name.setText(name);
}

你可能感兴趣的:(android)