Android: onTouch for Spans in Spannable Text

1.3k views Asked by At

I have a TextView containing Editable text. There are pictures in this text (drawables, I used Html.ImageGetter) for that I want to register onTouch events. So, when the user touches the image, which is part of a spannable text, I want to know that. (And, which image he touched).

Is that possible? If so, maybe without dirty workarounds?

Best regards, Jan Oliver Oelerich

1

There are 1 answers

1
EdenSphere On

Copied from the ArrowKeyMovementMethod source code, you could try to use the following snippet of code:

 private int getOffset(int x, int y, TextView widget){
  // Converts the absolute X,Y coordinates to the character offset for the
  // character whose position is closest to the specified
  // horizontal position.
  x -= widget.getTotalPaddingLeft();
  y -= widget.getTotalPaddingTop();

  // Clamp the position to inside of the view.
  if (x < 0) {
      x = 0;
  } else if (x >= (widget.getWidth()-widget.getTotalPaddingRight())) {
      x = widget.getWidth()-widget.getTotalPaddingRight() - 1;
  }
  if (y < 0) {
      y = 0;
  } else if (y >= (widget.getHeight()-widget.getTotalPaddingBottom())) {
      y = widget.getHeight()-widget.getTotalPaddingBottom() - 1;
  }

  x += widget.getScrollX();
  y += widget.getScrollY();

  Layout layout = widget.getLayout();
  int line = layout.getLineForVertical(y);

  int offset = layout.getOffsetForHorizontal(line, x);
  return offset;
}

Hope that helps, EdenSphere.