在 ListView 项目中突出显示搜索的文本 [英] Highlight searched text in ListView items
问题描述
我有一个 ListView
并且我正在使用自定义适配器来显示数据.现在我想像上面的屏幕截图一样更改搜索到的文本字母颜色.
I have a ListView
and i am using a custom adapter to show data. Now i want to change searched text letter colour as in above screen shot.
这是SearchView
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actionbar_menu_item, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
public boolean onQueryTextChange(String newText) {
// this is adapter that will be filtered
if (TextUtils.isEmpty(newText)){
lvCustomList.clearTextFilter();
}
else{
lvCustomList.setFilterText(newText.toString());
}
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
谢谢.
推荐答案
我假设你有一个自定义的 Adapter 并且已经实现了 getCount()
和 getView()
过滤项目,你只需要粗体部分.
I assume that you have a custom Adapter with getCount()
and getView()
implemented and already filtering items, and you just need the bold part.
要实现这一点,您需要使用 SpannableString
,基本上是带有标记的文本.例如,TextAppearanceSpan
可以用于更改字体、字体样式、大小和颜色.
To achieve that, you need to use a SpannableString
, which is basically text with markup attached. For example, a TextAppearanceSpan
can be used to change typeface, font style, size, and color.
因此,您应该更新适配器的 getView()
以将使用 textView.setText()
的部分更改为或多或少如下所示:
So, you should update your adapter's getView()
to change the part where you use textView.setText()
into something more or less like this:
String filter = ...;
String itemValue = ...;
int startPos = itemValue.toLowerCase(Locale.US).indexOf(filter.toLowerCase(Locale.US));
int endPos = startPos + filter.length();
if (startPos != -1) // This should always be true, just a sanity check
{
Spannable spannable = new SpannableString(itemValue);
ColorStateList blueColor = new ColorStateList(new int[][] { new int[] {}}, new int[] { Color.BLUE });
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
}
else
textView.setText(itemValue);
这篇关于在 ListView 项目中突出显示搜索的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!