【发布时间】:2015-03-12 11:41:46
【问题描述】:
我有一个列表视图并想从中搜索文本。我已经成功完成了,但现在我想搜索该项目并在列表视图中突出显示搜索到的文本。这是我在 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 用于此目的,但它不起作用。请帮助我并告诉我您是否需要任何其他相关代码。
编辑:
我遵循的教程来自here。我使用了相同的代码,但做了一些小的改动。我只想在列表视图中突出显示搜索到的文本(在这种情况下只有一项,例如国家/地区)。
【问题讨论】:
-
您没有将
spannable设置为任何视图。它刚刚创建,但没有在任何地方使用。 -
我也厌倦了将它设置为视图,但是当我打印它时,我得到的视图是空的。这就是我尝试过的
final ViewHolder holder = new ViewHolder();View view = inflater.inflate(R.layout.listview_item, null);holder.country = (TextView) view.findViewById(R.id.country);holder.country.setText(spannable); -
用你当前的代码更新你的答案,我会看看。
-
其实我是从androidbegin.com/tutorial/android-search-listview-using-filter这里下载的代码。我使用了相同的代码。我只是不知道如何突出显示搜索到的文本。请帮我。谢谢
标签: android listview android-listview listadapter