Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 683
FoamyGuy Avatar asked Jan 05 '11 00:01

FoamyGuy


People also ask

What is LinkMovementMethod?

android.text.method.LinkMovementMethod. A movement method that traverses links in the text buffer and scrolls if necessary. Supports clicking on links with DPad Center or Enter.

How do I use Linkify?

To call linkify in android, we have to call linkify. addLinks(), in that method we have to pass textview and LinkifyMask. Linkify. WEB_URLS: It going make URL as web url, when user click on it, it going to send url to default web browsers.

Is TextView clickable?

Just like Buttons and ImageViews we can add onClickListeners to TextViews by simply adding the attribute android:onClick="myMethod" to your TextView XML tag. The other way, TextView tv = (TextView) this.


1 Answers

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);
like image 94
astuetz Avatar answered Oct 22 '22 14:10

astuetz