Search code examples
javaandroidlinkify

How can I autolink @mentions in my adapter itemview?


I'm using Linkify to search for strings that come after the @symbol. Why don't they turn into links in my TextView? Do I have to set something else in the XML like android:linksClickable="true"?

feedItemView.messageText.setText(message.getString("messageText"));
Pattern userMatcher = Pattern.compile("\\B@[^:\\s]+");
String userViewURL = ".activity.UserProfileActivity://";
Linkify.addLinks(feedItemView.messageText, userMatcher, userViewURL);

Solution

  • I used the following code:

    feedItemView.messageText.setText(yeet.getString(ParseConstants.KEY_NOTIFICATION_TEXT));
    
    Linkify.TransformFilter filter = (match, url) -> match.group();
    
    Pattern mentionPattern = Pattern.compile("@([A-Za-z0-9_-]+)");
    String mentionScheme = "http://www.twitter.com/";
    Linkify.addLinks(feedItemView.messageText, mentionPattern, mentionScheme, null, filter);
    

    I also made sure to remove android:autoLink="all" from that TextView's XML. This will remove auto link functionality for web links so then you'd want to add this to method that handles displaying that TextView:

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