Android Linkify both web and @mentions all in the same TextView

FoamyGuy picture FoamyGuy · Jan 5, 2011 · Viewed 9.9k times · Source

Ok so I asked this yesterday:

AutoLink @mentions in a twitter client

I got my @mentions linking correctly. But in order to get it to work I had to take android:autoLink="web" out my xml for the TextView. So now I get links to @mentions but it no longer links URLs. I tried doing two seperate Linkify.addLinks() calls like this:

mentionFilter = new TransformFilter() {
    public final String transformUrl(final Matcher match, String url) {
        return match.group(1);
    }
};

// Match @mentions and capture just the username portion of the text.
//pattern = Pattern.compile("@([A-Za-z0-9_-]+)");
pattern = Pattern.compile("(@[a-zA-Z0-9_]+)");
scheme = "http://twitter.com/";

tweetTxt = (TextView) v.findViewById(R.id.tweetTxt);


Linkify.addLinks(tweetTxt, pattern, scheme, null, mentionFilter);
Linkify.addLinks(tweetTxt, Linkify.WEB_URLS);

But which ever gets called last is the one that gets applied. Can anyone tell me how I can make it link both the @mentions and still autoLink the URLs?

Edited to clarify some more of the code.

Answer

astuetz picture astuetz · Apr 13, 2012

Here's my code to linkify all Twitter links (mentions, hashtags and URLs):

TextView tweet = (TextView) findViewById(R.id.tweet);

TransformFilter filter = new TransformFilter() {
    public final String transformUrl(final Matcher match, String url) {
        return match.group();
    }
};

Pattern mentionPattern = Pattern.compile("@([A-Za-z0-9_-]+)");
String mentionScheme = "http://www.twitter.com/";
Linkify.addLinks(tweet, mentionPattern, mentionScheme, null, filter);

Pattern hashtagPattern = Pattern.compile("#([A-Za-z0-9_-]+)");
String hashtagScheme = "http://www.twitter.com/search/";
Linkify.addLinks(tweet, hashtagPattern, hashtagScheme, null, filter);

Pattern urlPattern = Patterns.WEB_URL;
Linkify.addLinks(tweet, urlPattern, null, null, filter);