简体   繁体   中英

How to prevent scroll of textview after set setMovementMethod for clickable span?

I have set clickable span on Textview , it makes TextView's scrolling enable. When i touch at clickable Span, TextView is scrolling.

But I want only clickable Textview with span but not want scrollable textview .

If anyone has idea then please share here.

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

and textview in 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" />

As LinkMovementMethod extends from ScrollingMovementMethod , it's quite difficult to disable its scrolling action. So I decided to write a custom one that extends from BaseMovementMethod .

All codes below are copied from LinkMovementMethod#onTouchEvent() . I only add one line of code.

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

Set these in TextView layout:

android:clickable="false"
android:focusable="false"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM