突出显示ListView项目中的搜索文本

Vik*_*uli 14 string search android listview

在此输入图像描述

我有一个ListView,我正在使用自定义适配器来显示数据.现在我想改变搜索文本字母颜色,如上面的屏幕截图.

这是代码 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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

mat*_*ash 27

我假设您有一个自定义适配器,getCount()getView()已实现并已经过滤项目,您只需要粗体部分.

要实现这一点,您需要使用a SpannableString,它基本上是带有标记的文本.例如,a TextAppearanceSpan可用于更改字体,字体样式,大小和颜色.

因此,您应该更新适配器getView()以将您使用的部分更改为textView.setText()或多或少的内容:

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);
Run Code Online (Sandbox Code Playgroud)