Created
July 30, 2012 15:22
-
-
Save kingori/3207764 to your computer and use it in GitHub Desktop.
linkified spannable generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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