LinkMovementMethod类有助于在 TextView 内查找、突出显示和处理对链接的点击,但在处理 onTouch() 方法时存在问题 - 如果您从检测到的链接开始拖动,您将看到不会发生滚动。
问问题
176 次
1 回答
1
ScrollSensitiveLinkMovementMethod具有更好的处理触摸并允许您在这种情况下滚动。
我想分享我的简单解决方案,可能会有所帮助。 https://gist.github.com/mpetlyuk/ec2d64659fbedfd47f7e0e650c9608dd 如果你喜欢它,你可以用星星取悦我:)
package your_package_name;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.method.Touch;
import android.text.style.ClickableSpan;
import android.view.MotionEvent;
import android.widget.TextView;
public class ScrollSensitiveLinkMovementMethod extends LinkMovementMethod {
private int CLICK_ACTION_THRESHOLD = 100;
private float startX;
private float startY;
private boolean isAClick(float startX, float endX, float startY, float endY) {
float differenceX = Math.abs(startX - endX);
float differenceY = Math.abs(startY - endY);
return !(differenceX > CLICK_ACTION_THRESHOLD || differenceY > CLICK_ACTION_THRESHOLD);
}
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
case MotionEvent.ACTION_UP:
float endX = event.getX();
float endY = event.getY();
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[] links = buffer.getSpans(off, off, ClickableSpan.class);
if (links.length != 0) {
if (action == MotionEvent.ACTION_UP && isAClick(startX, endX, startY, endY)) {
links[0].onClick(widget);
return true;
} else {
Selection.setSelection(buffer,
buffer.getSpanStart(links[0]),
buffer.getSpanEnd(links[0]));
}
} else {
Selection.removeSelection(buffer);
}
break;
}
return Touch.onTouchEvent(widget, buffer, event);
}
}
于 2018-06-30T08:18:37.173 回答