Having the textView with autoLinkMask set to Linkify.ALL, i\'m able to open the links and the browser shows the web-page.
I need to call a
I make @CommonsWare's code more elegant and clear by adding Click Listener which can be added directly into the same method which replace URL Spans.
Define YourCustomClickableSpan Class.
public static class YourCustomClickableSpan extends ClickableSpan {
private String url;
private OnClickListener mListener;
public YourCustomClickableSpan(String url, OnClickListener mListener) {
this.url = url;
this.mListener = mListener;
}
@Override
public void onClick(View widget) {
if (mListener != null) mListener.onClick(url);
}
public interface OnClickListener {
void onClick(String url);
}
}
Define RichTextUtils Class which will manipulate the Spanned text of your TextView.
public static class RichTextUtils {
public static Spannable replaceAll (
Spanned original,
Class sourceType,
SpanConverter converter,
final ClickSpan.OnClickListener listener) {
SpannableString result = new SpannableString(original);
A[] spans = result.getSpans(0, result.length(), sourceType);
for (A span : spans) {
int start = result.getSpanStart(span);
int end = result.getSpanEnd(span);
int flags = result.getSpanFlags(span);
result.removeSpan(span);
result.setSpan(converter.convert(span, listener), start, end, flags);
}
return (result);
}
public interface SpanConverter {
B convert(A span, ClickSpan.OnClickListener listener);
}
}
Define URLSpanConverter class which will do the actual code of replacement URLSpan with Your Custom Span.
public static class URLSpanConverter
implements RichTextUtils.SpanConverter {
@Override
public ClickSpan convert(URLSpan span, ClickSpan.OnClickListener listener) {
return (new ClickSpan(span.getURL(), listener));
}
}
Usage
TextView textView = ((TextView) this.findViewById(R.id.your_id));
textView.setText("your_text");
Linkify.addLinks(contentView, Linkify.ALL);
Spannable formattedContent = UIUtils.RichTextUtils.replaceAll((Spanned)textView.getText(), URLSpan.class, new UIUtils.URLSpanConverter(), new UIUtils.ClickSpan.OnClickListener() {
@Override
public void onClick(String url) {
// Call here your Activity
}
});
textView.setText(formattedContent);
Note that I defined all classes here as static so you can put it directly info your Util class and then reference it easily from any place.