Skip to content

Instantly share code, notes, and snippets.

@kingori
Created July 30, 2012 15:22
Show Gist options
  • Save kingori/3207764 to your computer and use it in GitHub Desktop.
Save kingori/3207764 to your computer and use it in GitHub Desktop.
linkified spannable generator
public static Spannable getLinkifiedSpannable(String text) {
Spannable spannable = new SpannableStringBuilder(text); //create spannable for linkify
Linkify.addLinks(spannable, Linkify.ALL); // make URLspan
URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class); //get url spans
for (URLSpan span : spans) { //iterate on url spans
int spanStart = spannable.getSpanStart(span); //save postion of current url span
int spanEnd = spannable.getSpanEnd(span);
if (spanStart < 0 || spanEnd < 0)
break;
String url = span.getURL();
spannable.removeSpan(span); //remove prev url span
spannable.setSpan(new URLSpan(url) { //make a new url span with custom click action and put it to the spannable
@Override
public void onClick(View widget) {
Uri uri = Uri.parse(getURL());
Context context = widget.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannable;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment