Is it possible to override URLSpan in TextView so it doesn't opens web view and I can handle clicks on it?

571 views Asked by At

I have a dynamic, custom String received from backend that contains a HTML markup <a href> tag.

The string is looking like this:

 "Some string from backend which have a `<a href="">`link`<a/>`. This string is passed to an app."

So in my Android app i want to still have a span appearance(bold link and etc as an URLSpan has), but I want to handle the clicks on my own. So I don't want to WebView be opened when i click on it, I want to override the clicks on it somehow.

Is it possible on Android?

I've tried something like this, but it is not working and I guess there is a simple way to do that (maybe not removing old span, and creating link appearance from scratch but just handle/override clicks on it somehow and not losing the link appearance?)

          bodyText.text = SpannableStringBuilder.valueOf(bodyText.text).apply {  
          getSpans(0, length, URLSpan::class.java)
                .forEach {
                //add new clickable span at the same position
                setSpan(
                    object : ClickableSpan() {
                        override fun onClick(widget: View) {
                            // trigger my own listener 
                            Toast.makeText(bodyText.context, "Clicked old span", Toast.LENGTH_SHORT).show();
                        }
                    },
                    getSpanStart(it),
                    getSpanEnd(it),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                )
           //remove old URLSpan
           removeSpan(it)
            }
        }

This code not working and it just removes the link from the text.

My case is that i want to show a Dialog when I touch a mentioned span and not fire webview.

1

There are 1 answers

0
subrat sahu On

    bodyText.text = SpannableStringBuilder.valueOf(text).apply {
                getSpans(0, length, URLSpan::class.java).forEach {
                    setSpan(
                    object : ClickableSpan() {
                        override fun onClick(widget: View) {
                            // trigger my own listener 
                            Toast.makeText(bodyText.context, "Clicked old span", Toast.LENGTH_SHORT).show();
                        }
                    },
                            getSpanStart(it),
                            getSpanEnd(it),
                            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                    )
                    removeSpan(it)
                }
            }
        // Include this to make links clickable
        movementMethod = LinkMovementMethod.getInstance()

You have to add bodyText.movementMethod = LinkMovementMethod.getInstance()