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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With