Skip to content

Instantly share code, notes, and snippets.

@dkajiwara
Created May 24, 2017 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkajiwara/45b7df5add1d5ad0a626c8f60c3482ba to your computer and use it in GitHub Desktop.
Save dkajiwara/45b7df5add1d5ad0a626c8f60c3482ba to your computer and use it in GitHub Desktop.
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