Creating Custom Link Strings in Android

To linkify your own data, you need to define your own linkify strings. Do this by creating a new RegEx pattern that matches the text you want to display as hyperlinks.

As with the native types, you can linkify the target Text View by calling Linkify.addLinks; however, rather than passing in one of the preset constants, pass in your RegEx pattern. You can also pass in a prefix that will be prepended to the target URI when a link is clicked.

Creating custom link strings in Linkify

// Define the base URI.
String baseUri = “content://com.paad.earthquake/earthquakes/”;
// Contruct an Intent to test if there is an Activity capable of 
// viewing the content you are Linkifying. Use the Package Manager
// to perform the test.
PackageManager pm = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(baseUri));
boolean activityExists = testIntent.resolveActivity(pm) != null;
// If there is an Activity capable of viewing the content
// Linkify the text.
if (activityExists) {
 int flags = Pattern.CASE_INSENSITIVE;
 Pattern p = Pattern.compile(“\\bquake[\\s]?[0-9]+\\b”, flags);
 Linkify.addLinks(myTextView, p, baseUri);
Linkify.addLinks(myTextView, p, baseUri,
 new MyMatchFilter(), new MyTransformFilter());

Using the Match Filter

To add additional conditions to RegEx pattern matches, implement the acceptMatch method in a Match Filter. When a potential match is found, acceptMatch is triggered, with the match start and end index (along with the full text being searched) passed in as parameters.

Using a Linkify Match Filter

class MyMatchFilter implements MatchFilter {
 public boolean acceptMatch(CharSequence s, int start, int end) {
 return (start == 0 || s.charAt(start-1) != ‘!’);

Leave a Comment