简体   繁体   中英

LinkMovementMethod stiff scrolling

I have an Activity with only a TextView. The TextView is long (requires vertical scrolling) and has some links.

In order to scroll and intercept links, I have the following code:

TextView textView = (TextView) getView().findViewById(R.id.help_text_view);
textView.setMovementMethod(LinkMovementMethod.getInstance());

The problem is the scrolling is "stiff," that is, you can't fling the text up and down like you would expect in most Views. The text just stops moving whenever the finger/cursor is lifted.

How can I get the normal fling functionality back?

My Solution is to create your own MovementMethod and implement the click by yourself

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

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