ClickableSpan strange behavior:onClick() called when clicking empty space

前端 未结 2 1622
轻奢々
轻奢々 2021-01-01 20:36

I have a TextView with ClickableSpan in that both layout_height and layout_width is wrap_content.

When the text in TextView in

相关标签:
2条回答
  • 2021-01-01 21:18

    I managed to solve it by extending LinkMovementMethod, and check whether the touch event offset is equals or bigger than the text lenght:

    public class MovementMethod extends LinkMovementMethod {
    
        @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);
    
                if (off >= widget.getText().length()) {
                   // Return true so click won't be triggered in the leftover empty space
                    return true;
                }
            }
    
            return super.onTouchEvent(widget, buffer, event);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 21:37

    Thanks for @dor506 for the answer, but it not work for gravity center, I have modified a little bit.

    @Override
            public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
                int action = event.getAction();
    
                if (action == MotionEvent.ACTION_UP) {
                    int x = (int) event.getX();
                    int y = (int) event.getY();
    
                    y -= widget.getTotalPaddingTop();
                    y += widget.getScrollY();
    
                    Layout layout = widget.getLayout();
                    int line = layout.getLineForVertical(y);
                    float lineLeft = layout.getLineLeft(line);
                    float lineRight = layout.getLineRight(line);
    
                    if (x > lineRight || (x >= 0 && x < lineLeft)) {
                        return true;
                    }
                }
    
                return super.onTouchEvent(widget, buffer, event);
            }
    
    0 讨论(0)
提交回复
热议问题