Control onclicklistener in autolink enabled textview

Viewed 14404

I am using a TextView for which I have set autolink="web" property in XML file. I have also implemented the onClickListener for this TextView. The problem is, when the text in TextView contains a hyperlink, and if I touch that link, the link opens in browser but simultaneously the onClickListener triggers too. I don't want that.

What I want is, if I touch the hyperlink the clickListener should not fire. It should only fire if I touch the part of the text that is not hyperlinked. Any suggestion?

9 Answers

Kotlin version:

Similar to older answers in Java. Simply:

  1. In Layout Editor/XML, add the types of things you'd like to hyperlink via the autoLink property.

    <TextView
        ...
        android:autoLink="web|phone|email" />
    
  2. Add an onClickListener to your TextView in Kotlin code to handle clicks on the plain text part. Check to make sure the person didn't click on a link by checking selectionStart and selectionEnd.

    binding.messageText.setOnClickListener { view ->
        if (binding.messageText.selectionStart == -1 && binding.messageText.selectionEnd == -1) {
            // do whatever you want when they click on the plain text part
        }
    }
    
Related