Question

I am trying to make clickable links in text strings that launch an activity when clicked. I have used Linkify() to detect links in my text. This function is capable of adding links to text, but only web URLs. I need to turn my output into a ClickableSpan so that I can implement this technique.

How do I get Linkify()'s identified links to become ClickableSpans which direct to an activity?

Below is the code I have used in Linkify:

// Linkify parameters
final static Pattern pattern = Pattern.compile("\\[[^]]*]"); // defines the fact that links are bound by [square brackets]
final String scheme = "http://"; // TODO: Currently this is just a blank link
Linkify.addLinks(linkText, pattern, scheme);
Was it helpful?

Solution

For what you want to achieve, it's probably simpler to just override the startActivity() method in your Activity and intercept the ACTION_VIEW intents with the URLs in your text. Something like this:

public class MyActivity extends Activity {

    @Override
    public void startActivity(Intent intent) {
        final String action = intent.getAction();
        if (action.equals(Intent.ACTION_VIEW)) {
            // launch our other activity instead
            Intent ourIntent = new Intent(this, MyOtherActivity.class);
            ourIntent.setData(intent.getData());
            super.startActivity(ourIntent);

            // we're done!
            return;
        }

        // else, normal handling by the framework
        super.startActivity(intent);
    }

    // the rest of your activity code

}

For reference, here's the source code for URLSpan which will trigger the startActivity() method above.

OTHER TIPS

How do I get Linkify()'s identified links to become ClickableSpans which direct to an activity?

After your call to addLinks(), call getText() to retrieve the Spanned object from the TextView. This object will have a series of URLSpan objects, one per matched link -- you can get an array of those through a call to getSpans(). You will need to note where each those spans start and end (via getSpanStart() and getSpanEnd()), remove the URLSpan, and replace it with your own spans to do what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top