【发布时间】:2015-08-16 04:06:25
【问题描述】:
我正在尝试在列表视图中实现搜索功能,例如浏览器中的文本搜索。
我已成功在光标数据中搜索输入词。但是找到匹配时如何更改相应单词的背景颜色?
这是bindview中的搜索代码
if (searchEnabled) {
cursor.moveToFirst();
while (cursor.moveToNext()) {
String cursorText = cursor.getString(indexMessage);
if (s.equals(searchText.toString())) {
//Change matched word's(textview) background color here
holder.textMessage.setBackgroundColor(Color.WHITE);
Log.i("Cursor Scan:", cursorText);
}
}
}
调用notifyDataSetChanged()后,只改变最后一行文本视图的颜色。
我尝试通过从getChildAt() 获取列表视图文本进行搜索并部分成功,但此视图不一致,它在滚动时达到其原始状态(因为此列表视图从光标膨胀)。
我尝试使用以下代码在列表视图文本中进行搜索:
private void updateListView(String textForSearch) {
LocalStoreDB localDB = new LocalStoreDB(getApplicationContext());
localMessageDB.openDB();
Cursor cursorForSearch = localDB.selectMessageDB();
cursorForSearch.moveToFirst();
while (cursorForSearch.moveToNext()) {
int position = cursorForSearch.getPosition();
View v = listview.getChildAt(position);
TextView tv = (TextView) v.findViewById(R.id.textMessage);
SpannableString cursorString = new SpannableString(tv.getText());
Pattern p = Pattern.compile(textForSearch);
Matcher m = p.matcher(cursorString);
while (m.find()) {
cursorString.setSpan(new BackgroundColorSpan(Color.WHITE),
m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.i("m.find()", cursorString.toString());
}
tv.setText(cursorString);
}
localDB.closeDB();
}
【问题讨论】: