I'm currently rendering HTML input in a TextView like so:
tv.setText(Html.fromHtml("<a href='test'>test</a>"));
The HTML being displayed is provided to me via an external resource, so I cannot change things around as I will, but I can, of course, do some regex tampering with the HTML, to change the href value, say, to something else.
What I want is to be able to handle a link click directly from within the app, rather than having the link open a browser window. Is this achievable at all? I'm guessing it would be possible to set the protocol of the href-value to something like "myApp://", and then register something that would let my app handle that protocol. If this is indeed the best way, I'd like to know how that is done, but I'm hoping there's an easier way to just say, "when a link is clicked in this textview, I want to raise an event that receives the href value of the link as an input parameter"
Another way, borrows a bit from Linkify but allows you to customize your handling.
Custom Span Class:
Helper function:
Usage:
Coming at this almost a year later, there's a different manner in which I solved my particular problem. Since I wanted the link to be handled by my own app, there is a solution that is a bit simpler.
Besides the default intent filter, I simply let my target activity listen to
ACTION_VIEW
intents, and specifically, those with the schemecom.package.name
This means that links starting with
com.package.name://
will be handled by my activity.So all I have to do is construct a URL that contains the information I want to convey:
In my target activity, I can retrieve this address:
In my example, I could simply check
data
for null values, because when ever it isn't null, I'll know it was invoked by means of such a link. From there, I extract the instructions I need from the url to be able to display the appropriate data.for who looks for more options here is a one
RESOURCE : CodePath
I changed the TextView's color to blue by using for example:
in the xml file. How to make it underlined is explained here.
Then use its onClick property to specify a method (I'm guessing you could call
setOnClickListener(this)
as another way), e.g.:In that method, I can do whatever I want as normal, such as launch an intent. Note that you still have to do the normal
myTextView.setMovementMethod(LinkMovementMethod.getInstance());
thing, like in your acitivity's onCreate() method.This answer extends Jonathan S's excellent solution:
You can use the following method to extract links from the text:
This can be used to remove one of the parameters in the
clickify()
method:A few changes to the ClickSpan:
Now you can simply set the text on the TextView and then add a listener to it: