Make TextView open links in CustomTabs

One of the basic features of TextView is recognizing URLs and transforming them into clickable spans. Once a link is clicked you are taken to the browser to view the link.

Under the hood

LinkMovementMethod handles the touch events inside the TextView, in order to decide wither the selection is occurring on particular region of the text. If the selection holds a region that is instance of URLSpan it calls onClick() method. Implementation simply does start intent with ACTION_VIEW action to open the selection (the link) in browser. But hey, we love CustomTabs!

Replace everything

Most reasonable way to bypass this short sightness of URLSpan is to replace it with our own Span. Implementing our own TransformationMethod will do the trick.

First, we linkify everything that looks, walks and quacks like a URL. 
Secondly, we replace all found ranges with our own CustomTabsURLSpan
Thirdly, we implement our logic inside onClick method of CustomTabsURLSpan to open the urls with CustomTabs, if that fails for whatever reason, we proceed with calling super method, which will open the link in browser.

Usage:

TextView textView = (TextView) findViewById(R.id.textview);
textView.setTransformationMethod(new LinkTransformationMethod());
textView.setMovementMethod(LinkMovementMethod.getInstance());