Created
June 27, 2018 19:52
-
-
Save liposo/ddfb50f98967c9cd4c25d0d78acc6fe0 to your computer and use it in GitHub Desktop.
Get urls from text and make then clickable (Android)
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
final List<String> extractedUrls = TextLink.extractUrls(imovel.descricao); | |
if (extractedUrls.size() > 0) { | |
for (final String link : extractedUrls) { | |
ClickableSpan normalLinkClickSpan = new ClickableSpan() { | |
@Override | |
public void onClick(View view) { | |
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link)); | |
startActivity(browserIntent); | |
} | |
}; | |
TextLink.makeLink(txtViewDescricao, link, normalLinkClickSpan); | |
} | |
} |
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
import java.util.List; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class TextLink { | |
public static void makeLink(TextView textView, String link, ClickableSpan clickableSpan) { | |
SpannableString spannableString = new SpannableString(textView.getText()); | |
int startIndexOfLink = textView.getText().toString().indexOf(link); | |
spannableString.setSpan(clickableSpan, startIndexOfLink, startIndexOfLink + link.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); | |
textView.setHighlightColor(Color.TRANSPARENT); // prevent TextView change background when highlight | |
textView.setMovementMethod(LinkMovementMethod.getInstance()); | |
textView.setText(spannableString, TextView.BufferType.SPANNABLE); | |
} | |
public static List<String> extractUrls(String text) { | |
List<String> containedUrls = new ArrayList<>(); | |
String urlRegex = "((https?|http|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"; | |
Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE); | |
Matcher urlMatcher = pattern.matcher(text); | |
while (urlMatcher.find()) { | |
containedUrls.add(text.substring(urlMatcher.start(0), | |
urlMatcher.end(0))); | |
} | |
return containedUrls; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment