1

Similar to this SO question, I'm trying to display clickable links in a TextView: How do I make links in a TextView clickable?

But I don't just want the link to open a website. I want to handle the click event myself and, say, launch an activity. Here is what I have so far:

myTextView.movementMethod = object: LinkMovementMethod() {
    override fun onTouchEvent(widget: TextView?, buffer: Spannable?, event: MotionEvent?): Boolean {

        doTheThing()

        return super.onTouchEvent(widget, buffer, event)
    }
}

And on my TextView:

android:text="Foo <a href="bar">Bar</a>"

As expected, "Bar" is underlined in blue, but the onTouchEvent is tripped whenever I click on the whole TextView, including on Foo. I only want it to fire when I tap "Bar" because that's what's underlined. Also, what if I had multiple links in the text? How would I get each one to respond differently?

Mike Miller
  • 3,368
  • 5
  • 36
  • 49
  • Possible duplicate of [handle textview link click in my android app](https://stackoverflow.com/questions/1697084/handle-textview-link-click-in-my-android-app) – Xenolion Oct 23 '17 at 15:25

1 Answers1

0

Split the string in to parts: Before link text, link text, after link text:

<string name="part_1">Here is a </string> <string name="link_text">link</string> <string name="part_2"> for you to tap</string>

Then use a SpannableStringBuilder to assemble the parts, and when you add the link text, set a ClickableSpan with the appropriate link handler on the span from the end of part 1 string to the end of the part 1 + link string:

SpannableStringBuilder builder = new SpannableStringBuilder(getString(R.string.part_1)); int spanStart = builder.length(); builder.append(getString(R.string.link_text)); int spanEnd = builder.length(); builder.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { // Do my thang } }, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); builder.append(getString(R.string.part_2)); textView.setText(builder); textView.setMovementMethod(LinkMovementMethod.getInstance());

Johnny C
  • 1,799
  • 1
  • 16
  • 27