Search code examples
androidlinkmovementmethod

Intercept link LinkMovementMethod with a Yes/No dialog


I have a standard LinkMovementMethod established in my TextView to push a web Activity of some sort when the user touches a link. However, I want to establish a "do you want to see the link" dialog rather than taking the user straight to the webpage. I've tried overriding the touch methods but it all gets a little convoluted. A little help?


Solution

  • You can accomplish it in two ways:

    • Create custom Spans: more complicated, but you can accomplish more customised text consisting of clickable parts (or bold, differently coloured etc). To know more, check out ClickableSpan and SpannableStringBuilder
    • Extend LinkMovementMethod to accept custom click listener

    In my opinion second solution is better in basic cases like yours. Here is how you can do it:

    1. Copy this java class: InternalLinkMovementMethod to your project
    2. 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));