Reputation: 5016
I'm already using android:autoLink
to make links clickable in TextView
, but the problem is that i need to check if the link starts with http
or www
because if the text is, for example, "some sentence.Error happens" it set the text as clickable and I want to avoid that. Any thought?
---------------- Here is the solution: ----------------
private void setUrlClickable(TextView textViewContent, Spanned text) {
SpannableString spannableString = new SpannableString(text);
final Matcher matcher = Pattern.compile("(http|www)\\S*").matcher(spannableString);
while (matcher.find()) {
spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.list_section)), matcher.start(), matcher.end(), 0);
spannableString.setSpan(new TextClickable(matcher.group(0)), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
textViewContent.setText(spannableString);
textViewContent.setMovementMethod(LinkMovementMethod.getInstance());
}
Upvotes: 2
Views: 187
Reputation: 71
Assuming your text look like this "this link www.yoursite.com is clickable" and you only want the "www.yoursite.com" part clickable you can do like this:
private void setText(String text){
String regexPattern = "(http|www)\\S*";
final Matcher matcher = Pattern.compile(regexPattern).matcher(text);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(text);
while(matcher.find()){
ClickableSpan clickable = new ClickableSpan() {
public void onClick(View view) {
// Do something with span.getURL() to handle the link click...
}
};
strBuilder.setSpan(clickable, matcher.start(), matcher.end(), 0);
}
}
hope that work for you.
Upvotes: 1
Reputation: 12986
You can use the Regular Expressions to validate the texts you want. For example you can use the following regex for to check if the string is http, ftp , ... link
String regex = "^(https?|ftp)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
And then create a checkText method to enable authoLink :
private static boolean checkText(String s, String regex) {
try {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
return matcher.matches();
} catch (RuntimeException e) {
return false;
}
Upvotes: 2