Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android autolink is too aggressive

Phones with SDK 20+ think that any two words with a dot between them is a link. How can I make my own Link detector?

android:autoLink="web" thinks abra.kadabra is an url.

setAutoLinkMask(Linkify.WEB_URLS); thinks abra.kadabra is an url.

Phones with SDK < 20 link everything correctly, the error happens only on when SDK is 20+.

Examples of what I've tried:

Code happening inside my custom TextView

SpannableString ss = new SpannableString(this.getText().toString());    
//LinkManager is a copy of Linkify but with another pattern.       
LinkManager.addLinks(ss, LinkManager.WEB_URLS);   
setText(ss);            
setMovementMethod(LinkMovementMethod.getInstance());   
setWebLinksTouchFeedback();

This didn't linkify anything. Even when I use Linkify instead of LinkManager

I have tried many other solutions, all which end up in linking nothing or everything. Any solution out there?

like image 771
pv-gni Avatar asked Oct 20 '22 10:10

pv-gni


1 Answers

You can make your own link detector using Matcher and Pattern classes and make them clickable with ClickableSpan.

String text = textView.getText().toString();

int i=0;
SpannableString spannableString = new SpannableString(text);
Matcher urlMatcher = Patterns.WEB_URL.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);
}

textView.setText(spannableString);
textView.setMovementMethod(new LinkMovementMethod());    

private static class GoToURLSpan extends ClickableSpan {
    String url;

    public GoToURLSpan(String url){
        this.url = url;
    }

    public void onClick(View view) {
        Uri webPage = Uri.parse(url); //http:<URL> or https:<URL>
        Intent intent = new Intent(Intent.ACTION_VIEW, webPage);
        view.getContext().startActivity(intent);
    }
}

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/text"
    android:text="Link http://google.com but dont link abra.kadabra"
    android:textColorLink="@color/accent"
    android:textColorHighlight="@color/accent" />

Replace Pattern.WEB_URL with your own. You can find some url patterns in StackOverflow.

like image 139
Pedro Avatar answered Oct 21 '22 23:10

Pedro