如何在为可点击范围设置setMovementMethod后阻止textview的滚动?

时间:2016-09-24 07:00:15

标签: java android scroll textview

我在clickable span上设置了Textview,它使TextView's滚动启用。当我触摸可点击的跨度时,TextView正在滚动。

但我只希望点击Textview span但不想要scrollable textview

如果有人有想法,请分享到这里。

textViewPostText.setMovementMethod(LinkMovementMethod.getInstance());
                ss.setSpan(clickableSpan, 0, s.length(), 0);
textview

xml

<TextView
            android:id="@+id/textViewPostText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/view1"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:maxLines="2"
            android:ellipsize="end"
            android:text=""
            android:textSize="15dp" />

1 个答案:

答案 0 :(得分:1)

LinkMovementMethodScrollingMovementMethod延伸时,禁用其滚动操作非常困难。所以我决定编写一个从BaseMovementMethod扩展的自定义版本。

以下所有代码均来自LinkMovementMethod#onTouchEvent()。我只添加一行代码。

public class ClickOnlyMovementMethod extends BaseMovementMethod {

  @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);

      ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

      if (link.length != 0) {
        if (action == MotionEvent.ACTION_UP) {
          link[0].onClick(widget);
          // Add this line of code for removing the selection effect 
          // when your finger moves away
          Selection.removeSelection(buffer);
        } else if (action == MotionEvent.ACTION_DOWN) {
          Selection.setSelection(buffer,
              buffer.getSpanStart(link[0]),
            buffer.getSpanEnd(link[0]));
        }

        return true;
      } else {
        Selection.removeSelection(buffer);
      }
    }
    return super.onTouchEvent(widget, buffer, event);
  }
}