After facing the same issue as well, please consider, there seems to be a certain sequence of setting the methods.
- Get the 'TextView'
final TextView tv = new TextView(getContext());
- Set all necessary layout parameter
tv.setLayoutParams(lp_tv);
- Set the
Linkify
to mark all links in the text as Link
tv.setAutoLinkMask(Linkify.ALL);
- Set the content of the
TextView
(after the setAutoLinkMask
)
tv.setText("MyText")
tv.setText(Html.fromHtml("<big>MyText</big>");
- Now you can attach the
LinkMovementMethod
. If the method is attached earlier, it will call the default behavior and open the system browser. I use a TextViewLinkHandler
class to do the job as individual behavior. The standard behavior is:
tv.setLinkMovementMethod(new LinkMovementMethod.getInstance());
I use the TextViewLinkHandler
to do some other stuff if the user clicks a link (e.g. opening an individual Intent to process the URL)
tv.setMovementMethod(new TextViewLinkHandler() {
// do my stuff ...
// if left blank, nothing will happen on click at the link, so leave it blank to do nothing
});
With the mentioned TextViewLinkHandler()
public abstract class TextViewLinkHandler extends LinkMovementMethod {
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_UP)
return super.onTouchEvent(widget, buffer, event);
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);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
onLinkClick(link[0].getURL());
}
return true;
}
abstract public void onLinkClick(String url);
}