我有一个使用自定义适配器将字符串集合绑定到的 ListView。我还强调了文本中的某些关键字。我正在使用 SpannableString 和正则表达式在单词下划线,但我想知道这是否是最有效的方法?我注意到 java.util.regex.Matcher 和 regex.util.regex.Pattern 类的分配跟踪器中有很多分配,这可能会导致我的应用程序出现内存泄漏。我知道正则表达式可能很昂贵,但我不确定另一种方法来做我需要做的事情。
public class Main extends ListActivity
{
private static CustomAdapter adapter = null;
private static List<Keyword> keywords;
private static Matcher matcher;
@Override
public void onCreate(Bundle icicle)
{
List<Item> items = new ArrayList<Item>();
keywords = GetKeywords();
items = GetItems();
adapter = new CustomAdapter();
for (Item item : items)
adapter.addItem(item);
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
/* ADAPTER */
private class CustomAdapter extends BaseAdapter
{
private final List<Item> mData = new ArrayList<Item>();
private final LayoutInflater mInflater;
public CustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Item item) {
mData.add(item);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
final Item item = (Item)this.getItem(position);
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.main, parent, false);
holder.text = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.text.setText(Highlight(item.getTitle(), keywords, matcher), BufferType.SPANNABLE);
return(convertView);
}
}
static class ViewHolder {
TextView text, date, site;
}
private SpannableString Highlight(String text, List<Keyword> keywords, Matcher matcher)
{
final SpannableString content = new SpannableString(text);
for (Keyword keyword : keywords)
{
matcher = Pattern.compile("\\b" + keyword + "\\b").matcher(text);
if (matcher.find())
{
start = matcher.start();
end = matcher.end();
content.setSpan(new UnderlineSpan(), start, end, 0);
}
}
}
return content;
}
}