我有一个listview,想从中搜索文本。我已经成功完成了,但是现在我想搜索该项目并在列表视图中突出显示搜索到的文本。这是我在ListViewAdapter中的过滤器功能:
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (WorldPopulation wp : arraylist)
{
// Find charText in wp
int startPos = wp.getCountry().toLowerCase(
Locale.getDefault()).indexOf(charText.toLowerCase(Locale.getDefault()));
int endPos = startPos + charText.length();
if (startPos != -1)
{
Spannable spannable = new SpannableString(wp.getCountry());
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);
// countryTextView.setText(spannable);
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
我已经用谷歌搜索了,我知道Spannable用于此目的,但是它不起作用。请帮助我,告诉我是否需要其他相关代码。
编辑:
我遵循的教程是从这里开始的。我使用相同的代码进行了一些小的更改。我只想在列表视图中突出显示搜索到的文本(在这种情况下,仅是一项,例如国家/地区)。
好吧,我下载了示例项目,最后附带了以下内容。使代码适应您的需求。
在您的过滤器方法中,存储用于执行过滤器的字符串:
// Filter Class
public void filter(String searchString) {
this.searchString = searchString;
...
// Filtering stuff as normal.
}
您必须声明一个成员字符串来存储它:
public class ListViewAdapter extends BaseAdapter {
...
String searchString = "";
...
并且,在getView
您突出显示搜索词:
public View getView(final int position, View view, ViewGroup parent) {
...
// Set the results into TextViews
WorldPopulation item = worldpopulationlist.get(position);
holder.rank.setText(item.getRank());
holder.country.setText(item.getCountry());
holder.population.setText(item.getPopulation());
// Find charText in wp
String country = item.getCountry().toLowerCase(Locale.getDefault());
if (country.contains(searchString)) {
Log.e("test", country + " contains: " + searchString);
int startPos = country.indexOf(searchString);
int endPos = startPos + searchString.length();
Spannable spanText = Spannable.Factory.getInstance().newSpannable(holder.country.getText()); // <- EDITED: Use the original string, as `country` has been converted to lowercase.
spanText.setSpan(new ForegroundColorSpan(Color.RED), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.country.setText(spanText, TextView.BufferType.SPANNABLE);
}
...
}
希望能帮助到你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句