Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Fixed android autolink is too aggressive
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.view.View;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AutoLinkTextView extends AppCompatTextView {
private static final Pattern URL_PATTERN =
Pattern.compile("(http://|https://){1}[\\w\\.\\-/:\\#\\?\\=\\&\\;\\%\\~\\+]+", Pattern.CASE_INSENSITIVE);
public AutoLinkTextView(Context context) {
super(context);
}
public AutoLinkTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AutoLinkTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* Sets the text to be displayed.<br>
*
* Workaround: below issue.
* ref:https://stackoverflow.com/questions/30528825/android-autolink-is-too-aggressive<br>
* @param text
*/
public void setTextWithUrl(CharSequence text) {
int i=0;
SpannableString spannableString = new SpannableString(text);
Matcher urlMatcher = URL_PATTERN.matcher(text);
while(urlMatcher.find()) {
String url = urlMatcher.group(i);
int start = urlMatcher.start(i);
int end = urlMatcher.end(i++);
spannableString.setSpan(new GoToURLSpan(url), start, end, 0);
}
setMovementMethod(new LinkMovementMethod());
setText(spannableString);
}
private static class GoToURLSpan extends ClickableSpan {
String url;
private GoToURLSpan(String url){
this.url = url;
}
public void onClick(View view) {
Uri webPage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webPage);
view.getContext().startActivity(intent);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment