Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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.

like image 389
Code Droid Avatar asked Apr 02 '12 19:04

Code Droid


1 Answers

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());
like image 156
MH. Avatar answered Oct 21 '22 10:10

MH.