Last active
November 10, 2016 05:18
-
-
Save xingstarx/5edc9ad7137241488a2dc67f4f84f1b2 to your computer and use it in GitHub Desktop.
自定义LinkMovementMethod处理textview的链接点击事件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private final RectF touchedLineBounds = new RectF(); | |
@Override | |
public boolean onTouchEvent(TextView widget, Spannable buffer, | |
MotionEvent event) { | |
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); | |
touchedLineBounds.left = layout.getLineLeft(line); | |
touchedLineBounds.top = layout.getLineTop(line); | |
touchedLineBounds.right = layout.getLineWidth(line) + touchedLineBounds.left; | |
touchedLineBounds.bottom = layout.getLineBottom(line); | |
if (touchedLineBounds.contains(x, y)) { | |
final ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); | |
if (link.length == 0) { | |
Selection.removeSelection(buffer); | |
return Touch.onTouchEvent(widget, buffer, event); | |
} | |
ClickableSpan targetObj = link[0]; | |
if (action == MotionEvent.ACTION_UP) { | |
URLSpan urlSpan = (URLSpan) targetObj; | |
handlerTouchEvent(urlSpan, widget); | |
} else if (action == MotionEvent.ACTION_DOWN) { | |
Selection.setSelection(buffer, buffer.getSpanStart(targetObj), buffer.getSpanEnd(targetObj)); | |
} | |
return true; | |
} | |
} | |
return Touch.onTouchEvent(widget, buffer, event); | |
} | |
public abstract void handlerTouchEvent(URLSpan urlSpan, TextView widget); |
touchedLineBounds.left = layout.getLineLeft(line);
touchedLineBounds.top = layout.getLineTop(line);
touchedLineBounds.right = layout.getLineWidth(line) + touchedLineBounds.left;
touchedLineBounds.bottom = layout.getLineBottom(line);
关键代码是这个
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
处理了点击事件,对于点击处在链接之外的做了处理,
touchedLineBounds.contains(x, y)
这个就是判断点击的点,是否是在链接上,如果不在,就不触发打开链接,或者是其他自定义的业务。touchedLineBounds的判断是出自于
https://github.com/Saketme/Better-Link-Movement-Method