Skip to content

Instantly share code, notes, and snippets.

@wcoder
Last active July 14, 2021 15:24
Show Gist options
  • Save wcoder/b8be47ba8ba583a6e6ac46524d35a386 to your computer and use it in GitHub Desktop.
Save wcoder/b8be47ba8ba583a6e6ac46524d35a386 to your computer and use it in GitHub Desktop.
Generic Xamarin.Android method to find Span in TextView for implementation custom LinkMovementMethod.OnTouchEvent
private T FindSpan<T>(TextView textView, ISpannable spannable, MotionEvent e)
where T : Java.Lang.Object
{
var x = (int)e.GetX() - textView.TotalPaddingLeft + textView.ScrollX;
var y = (int)e.GetY() - textView.TotalPaddingTop + textView.ScrollY;
var layout = textView.Layout;
int position = layout.GetOffsetForHorizontal(layout.GetLineForVertical(y), x);
var links = spannable.GetSpans(position, position, Java.Lang.Class.FromType(typeof(T)));
if (links.Length > 0 && IsPositionWithinTag(position, spannable, links[0]))
{
return links[0] as T;
}
return default;
}
private bool IsPositionWithinTag(int position, ISpannable spannable, Java.Lang.Object tag)
{
return position >= spannable.GetSpanStart(tag) && position <= spannable.GetSpanEnd(tag);
}
/* USING:
//...
public override bool OnTouchEvent(TextView textView, ISpannable spannable, MotionEvent e)
{
//...
var clickableSpan = FindSpan<ClickableSpan>(textView, spannable, e);
//...
}
//...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment