8

I want to make several parts of text individually clickable for example in the text below:

Get the weather forcast one day, two day, seven day.

I want to be able to click individually three different regions of the text to get one day, two day or seven day forcast. I don't want this to goto a web page URL but just catch the click on the region of text inside the activity that is showing the TextView.

Code Droid
  • 10,344
  • 17
  • 72
  • 112
  • possible duplicate of [How to click or tap on a TextView text on different words?](http://stackoverflow.com/questions/9584136/how-to-click-or-tap-on-a-textview-text-on-different-words) – ForceMagic Oct 29 '13 at 22:01

1 Answers1

16

You should be able to accomplish that using ClickableSpan. Basically you need to create a SpannableStringBuilder, append the text parts and set a different ClickableSpan for each clickable text part.

SpannableStringBuilder sb = new SpannableStringBuilder();
String regularText = "This text is ";
String clickableText = "clickable";
sb.append(regularText);
sb.append(clickableText);
sb.setSpan(new ClickableSpan(), sb.length()-clickableText.length(), sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView tv = ...
tv.setText(sb);

This is just an example illustrating how to set a single ClickableSpan. Obviously it will make more sense to do above in a loop and set a new span with each iteration.

However, since ClickableSpan is an abstract class, you'll first need to extend it with your own concrete implementation. More specifically, the onClick method will need to be implemented to handle click events.

Also, don't forget to set a MovementMethod to the TextView, e.g. LinkMovementMethod:

tv.setMovementMethod(LinkMovementMethod.getInstance());
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
MH.
  • 45,303
  • 10
  • 103
  • 116