最近开发遇到listView中解析爬虫回来的html数据超链接点击问题。有文字html标签链接和纯网址链接混合。链接点击效果是有了但listview的item点击事件却失效了。现将解决办法和网友们分享下:
主要代码:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView==null) {
holder = new ViewHolder();
convertView = View.inflate(context, R.layout.list_item, null);
holder.mtext = (TextView) convertView.findViewById(R.id.linktest);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
((ViewGroup)convertView).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);//加上次属性使焦点能够传递
Spanned html = Html.fromHtml(list.get(position));
Object[] spans = html.getSpans(0, html.length(), URLSpan.class);
holder.mtext.setAutoLinkMask(Linkify.WEB_URLS);
holder.mtext.setMovementMethod(LinkMovementMethod.getInstance());
holder.mtext.setText(html);
SpannableString ss = (SpannableString) holder.mtext.getText();
for (int i = 0; i < spans.length; i++) {
URLSpan span = (URLSpan) spans[i];
int end = html.getSpanEnd(span);
int start = html.getSpanStart(span);
ss.setSpan(span, start, end, 0);
}
holder.mtext.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
boolean ret = false;
CharSequence text = ((TextView) v).getText();
Spannable stext = Spannable.Factory.getInstance().newSpannable(text);
TextView widget = (TextView) v;
int action = event.getAction();
if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = stext.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(widget);
}
ret = true;
}
}
return ret;
}
});
return convertView;
}
参考:ListView: TextView with LinkMovementMethod makes list item unclickable?