我有一个只有TextView的Activity。 TextView很长(需要垂直滚动)并且有一些链接。
为了滚动和拦截链接,我有以下代码:
TextView textView = (TextView) getView().findViewById(R.id.help_text_view);
textView.setMovementMethod(LinkMovementMethod.getInstance());
问题是滚动是“僵硬的”,也就是说,你不能像大多数视图中所期望的那样上下翻动文本。只要手指/光标被抬起,文本就会停止移动。
如何恢复正常的投掷功能?
答案 0 :(得分:4)
我的解决方案是创建自己的MovementMethod并自行实现点击
private MovementMethod createMovementMethod ( Context context ) {
final GestureDetector detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp ( MotionEvent e ) {
return true;
}
@Override
public boolean onSingleTapConfirmed ( MotionEvent e ) {
return true;
}
});
return new ScrollingMovementMethod() {
@Override
public boolean onTouchEvent ( @NotNull TextView widget, @NotNull Spannable buffer, @NotNull MotionEvent event ) {
// check if event is a single tab
boolean isClickEvent = detector.onTouchEvent(event);
// detect span that was clicked
if (isClickEvent) {
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) {
// execute click only for first clickable span
// can be a for each loop to execute every one
link[0].onClick(widget);
return true;
}
}
// let scroll movement handle the touch
return super.onTouchEvent(widget, buffer, event);
}
};
}