Created
February 25, 2015 17:15
-
-
Save Narfss/aaff46d75c4e522ddef0 to your computer and use it in GitHub Desktop.
Spanned text with intercepting click url event in a Html text formated.
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
package com.fmSirvent.testApp.utils; | |
import android.content.Intent; | |
import android.net.Uri; | |
import android.text.Html; | |
import android.text.ParcelableSpan; | |
import android.text.SpannableString; | |
import android.text.Spanned; | |
import android.text.style.ClickableSpan; | |
import android.text.style.URLSpan; | |
import android.view.View; | |
import android.widget.Toast; | |
/** | |
* Created by fmSirvent on 25/2/15. | |
*/ | |
public class TrackedHtml { | |
public static android.text.Spanned fromHtml(java.lang.String source) { | |
Spanned spanned = Html.fromHtml(source); | |
SpannableString finalText = new SpannableString(spanned.toString()); | |
//Replace the UrlSpan with a custom ClickSpan | |
URLSpan[] spans = spanned.getSpans(0, source.length()-1, URLSpan.class); | |
for (URLSpan urlSpan : spans){ | |
final int startWord = spanned.getSpanStart(urlSpan); | |
final int endWord = spanned.getSpanEnd(urlSpan); | |
ClickSpan span = new ClickSpan(urlSpan.getURL()); | |
finalText.setSpan(span, startWord, endWord, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); | |
} | |
//Adding the rest of spans. | |
ParcelableSpan[] allSpans = spanned.getSpans(0, source.length()-1, ParcelableSpan.class); | |
for (ParcelableSpan parcelableSpan : allSpans){ | |
if (!(parcelableSpan instanceof URLSpan)) { | |
final int startWord = spanned.getSpanStart(parcelableSpan); | |
final int endWord = spanned.getSpanEnd(parcelableSpan); | |
finalText.setSpan(parcelableSpan, startWord, endWord, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); | |
} | |
} | |
return finalText; | |
} | |
public static class ClickSpan extends ClickableSpan { | |
private String url; | |
public ClickSpan(String url) { | |
this.url = url; | |
} | |
@Override | |
public void onClick(View widget) { | |
//Track the link clicked here. | |
Toast.makeText(widget.getContext(), "OpenUrl: " + url, Toast.LENGTH_LONG).show(); | |
Intent i = new Intent(Intent.ACTION_VIEW); | |
i.setData(Uri.parse(url)); | |
widget.getContext().startActivity(i); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment