/** 判断是否有ClickaSpan被点击,并处理的Touch事件分配 */ public classLocalLinkMovementMethod extends LinkMovementMethod { private staticLocalLinkMovementMethod sInstance;
public staticLocalLinkMovementMethod getInstance() { if (sInstance == null) sInstance = newLocalLinkMovementMethod(); return sInstance; }
public booleanonTouchEvent(TextView widget, Spannable buffer, MotionEventevent) { int action =event.getAction(); // 参考父类,只判断up和downn事件 if (action ==MotionEvent.ACTION_UP || action ==MotionEvent.ACTION_DOWN) { // 获取手指触摸位置的ClickableSpan ClickableSpan[]link = getOnClickSpan(widget, buffer, event); if (link.length != 0) { // 如果手指触摸位置有ClickableSpan,则down事件拦截Touch事件 if (action ==MotionEvent.ACTION_DOWN) { ((MyTextView)widget).linkHit = true; } else if (action ==MotionEvent.ACTION_UP) { ((MyTextView)widget).linkHit = false; } } } // 交由父类处理点击事件分发。此处的返回值并不影响touch事件的分发,TextView的touch事件只受linkHit影响 return super.onTouchEvent(widget,buffer, event); }
/** 参考父类,获取触摸位置的ClickableSpan */ privateClickableSpan[] getOnClickSpan(TextView widget, Spannable buffer,MotionEvent event) { 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);
returnbuffer.getSpans(off, off, ClickableSpan.class); } } |