要实现如下效果:
之前:
action_down:
松开之后,又回到第一个图片状态:
主要是实现LinkMovementMethod继承类,然后重写ontouchevent就ok了
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
// TODO Auto-generated method stub
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 = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(widget);
buffer.setSpan(new BackgroundColorSpan(Color.TRANSPARENT),
buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if (action == MotionEvent.ACTION_DOWN) {
buffer.setSpan(new BackgroundColorSpan(Color.GRAY),
buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Selection.setSelection(buffer,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
}
return true;
} else {
Selection.removeSelection(buffer);
}
}
return Touch.onTouchEvent(widget, buffer, event);
}
clickspan中的onclick:
@Override
public void onClick(View widget) {
// ((TextView)widget).setTextColor(Color.RED);
Spannable spannable = ((Spannable)((TextView)widget).getText());
Selection.removeSelection(spannable);
// Selection.setSelection(spannable, 0);
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
}
主要是上面的两个点
参见:http://my.oschina.net/djone/blog/145057
http://stackoverflow.com/questions/16792963/android-clickablespan-intercepts-the-click-event
http://gundumw100.iteye.com/blog/851009
demo链接:http://download.csdn.net/detail/swust_chenpeng/6694065