Guillaume
Guillaume

Reputation: 22822

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 TextView, with these two caveats:

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(R.id.description);
final Spannable span = Spannable.Factory.getInstance().newSpannable("the full text for the view");
span.setSpan(new ClickableSpan() {
    @Override
    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
descriptionTextView.setText(span);
descriptionTextView.setMovementMethod(LinkMovementMethod.getInstance());

Upvotes: 8

Views: 2308

Answers (2)

Fritz Saint-Paul
Fritz Saint-Paul

Reputation: 1

In completion of previous post this might help some one

        TextView textView = (TextView) getView().findViewById(R.id.textView);
        textView.setText(Html.fromHtml(getString(R.string.html_)) , TextView.BufferType.SPANNABLE);

        String tmp = ((Spannable) textView.getText()).toString();
        String linkText = getString(R.string.html_link);
        int index = tmp.indexOf(linkText);

        if(index>=0) {
            Spannable spannable = (Spannable) textView.getText() ;
            spannable.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    try {
                        /// do what you must

                    }catch (Exception ex){
                        handleException(ex);
                    }
                }
            }, index, index+getString(R.string.html_link).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(spannable);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        }

Upvotes: 0

kabuko
kabuko

Reputation: 36302

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.

Upvotes: 6

Related Questions