As you all know, we can set click listener on textview like we use to set it in other controls (Button, ImageView etc).
- textview.setOnClickListener(new View.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- }
- });
If the object of ClickableSpan is attached with TextView with a movement method of LinkmovementMethod, the text click will call onClick(View) method.
Syntax
- ClickableSpan clickableSpan = new ClickableSpan()
- {
- @Override
- public void onClick(View textView)
- {
- }
- @Override
- public void updateDrawState(TextPaint ds)
- {
- super.updateDrawState(ds);
- }
- };
- SpannableString ss =new SpannableString("This is demo android program");
- ss.setSpan(clickableSpan,13,19,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- object of ClickableSpan.
- start position of text
- end position of text
Now you need to set that text in your TextView and most importantly, set setMovementMethod() on TextView.
- textView.setText(ss);
- textView.setMovementMethod(LinkMovementMethod.getInstance());
Let’s see one example program for more than one click listener on TextView.
activity_main.xml
- <RelativeLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:padding="20dp">
- <TextView android:id="@+id/txtData"
- android:layout_width="wrap_content"
- android:textAppearance="?android:attr/textAppearanceLarge"
- android:layout_height="wrap_content" />
- </RelativeLayout>
- public class MainActivity extends Activity
- {
- private TextView txtData;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- txtData = (TextView) findViewById(R.id.txtData);
- String text = "I love to do programming in @Android @IOS @JAVA";
- SpannableString spanString = new SpannableString(text);
- Matcher matcher = Pattern.compile("@([A-Za-z0-9_-]+)").matcher(spanString);
- while (matcher.find())
- {
- spanString.setSpan(new ForegroundColorSpan(Color.parseColor("#0000FF")), matcher.start(), matcher.end(), 0); //to highlight word havgin '@'
- final String tag = matcher.group(0);
- ClickableSpan clickableSpan = new ClickableSpan()
- {
- @Override
- public void onClick(View textView)
- {
- Log.e("click", "click " + tag);
- String searchText = tag.replace("@", ""); //replace '@' with blank character to search on google.
- Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/search?q=" + searchText));
- startActivity(browserIntent);
- }
- @Override
- public void updateDrawState(TextPaint ds)
- {
- super.updateDrawState(ds);
- }
- };
- spanString.setSpan(clickableSpan, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
- txtData.setText(spanString);
- txtData.setMovementMethod(LinkMovementMethod.getInstance());
- }
- }

Join the conversation! Your thoughts help the community grow.