Android: Linkify TextView Android: Linkify TextView android android

Android: Linkify TextView


The easy way is put autoLink in XML layout.

  android:autoLink="web" 


I created a static method that does this simply:

/** * Add a link to the TextView which is given. *  * @param textView the field containing the text * @param patternToMatch a regex pattern to put a link around * @param link the link to add */public static void addLink(TextView textView, String patternToMatch,        final String link) {    Linkify.TransformFilter filter = new Linkify.TransformFilter() {        @Override public String transformUrl(Matcher match, String url) {            return link;        }    };    Linkify.addLinks(textView, Pattern.compile(patternToMatch), null, null,            filter);}

And the OP could use it simply:

addLink(text, "^Android", "http://www.android.com");


I don't have much experience with Linkify. So far all I have wanted to do is make urls in the text into links which is handled automatically by a different version of addLinks.

However the regular expression you are using to match on "Android" can be changed to only match the one that starts the string by tweaking your regular expression:

Pattern pattern = Pattern.compile("^Android");

Notice the addition of '^'. This tells the regular expression matcher to only match the pattern 'Android' when it starts the string. If that will work with your strings then great. If you have other cases were the word you want to link is not at the beginning of the line you will need to explore regular expressions some more. I recommend this site to learn more regular-expressions.info