? ? ?最近開發(fā)遇到listView中解析爬蟲回來的html數(shù)據(jù)超鏈接點(diǎn)擊問題梳星。有文字html標(biāo)簽鏈接和純網(wǎng)址鏈接混合掖举。鏈接點(diǎn)擊效果是有了但listview的item點(diǎn)擊事件卻失效了。現(xiàn)將解決辦法和網(wǎng)友們分享下:
主要代碼:
@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);//加上次屬性使焦點(diǎn)能夠傳遞
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?