Search code examples
androidhtmlandroid-webviewandroid-viewandroid-spannable

Android. How to get substring from Spannable which was clicked?


I have html string:

htmlString = "This is a <a href=\"https://translate.google.com/\">link</a> and another link <a href=\"https://google.com/\">link2</a>"

I set this String to my TextView. Here is my code:

tvText.setText(Html.fromHtml(htmlString));

And also I set LinkMovementMethod, links to be clickable.

tvText.setMovementMethod(LinkMovementMethod.getInstance());

Everything is fine, but links open in the browser by default, and I need to open them inside the application in web view.

Can I somehow get the link from the clicked String ? So that I can load the link in web view.

Or do I need to manually search for all links in the String and put clicks on them (ClickableSpan)? Please, help me.


Solution

  • Here is how you can do it:

    Extend LinkMovementMethod to accept custom click listener

    Copy this java class: InternalLinkMovementMethod to your project Add set the link movement method of your TextView to this custom one, providing a click listener:

    OnLinkClickedListener clickListener = new OnLinkClickedListener() {
        @Override
        public boolean onLinkClicked(String linkText) {
            // here you can handle your click, eg show the dialog
            // `linkText` is the text being clicked (the link)
            // return true if handled, false otherwise
        }
    }
    
    yourTextView.setMovementMethod(new InternalLinkMovementMethod(clickListener)
    

    Base on: Intercept link LinkMovementMethod with a Yes/No dialog