Android Clickable TextView How To Make Multiple Click Regions on Text And Catch Region Selection [closed]
Asked Answered
N

1

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.

Nephritis answered 2/4, 2012 at 19:1 Comment(1)
possible duplicate of How to click or tap on a TextView text on different words?Redmer
R
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());
Rolfrolfe answered 2/4, 2012 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.