Guillaume Guillaume - 1 year ago 66
Android Question

Android: add "internal" links to part of a TextView, that links to action in my code

As the title explains, I'd like to add links to my

, with these two caveats:

  • I want the link to act on a part of the
    , not the full one (something like an
    anchor in HTML).

  • I want the link to point to an action in my code, not a website. I could define a method in my activity, or implement an
    , and execute that when that specific link is clicked.

So far, I succeeded to turn phone numbers, addresses, web sites and emails into dedicated external links using:

Linkify.addLinks(message, Linkify.ALL);

I'd like something similar for internal links (to my method), with the possibility to define custom ones.

Also, using a web page with internal link and a web view is not really an option, as I already have several complex layouts defined, and having to modify the whole application and concepts would be quite a pain...

Any idea?

EDIT: Kabuko gave me a very good solution, here is exactly how I implemented it:

final TextView descriptionTextView = (TextView) findViewById(;
final Spannable span = Spannable.Factory.getInstance().newSpannable("the full text for the view");
span.setSpan(new ClickableSpan() {
public void onClick(View widget) {
Toast.makeText(StartEventActivity.this, "LINK CLICKED", Toast.LENGTH_SHORT).show();
}, 1, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // 1 and 20 to be replaced with actual index of start and end of the desired link

Answer Source

If you wanted to actually go to URLs you could use Html.fromHtml, but if you want your own click handlers you can use a ClickableSpan.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download