Friday, 22 July 2011

Android: how to make only part of a Textview string clickable

Say you have a string "Some text [clickable]" which you want to add to a TextView and you only want the "[clickable]" part of the string to be clickable. The way to go about it is to add the following code to your Activity class:

TextView myTextView = new TextView(this);
String myString = "Some text [clickable]";
int i1 = myString.indexOf("[");
int i2 = myString.indexOf("]");
myTextView.setText(myString, BufferType.SPANNABLE);
Spannable mySpannable = (Spannable)myTextView.getText();
ClickableSpan myClickableSpan = new ClickableSpan()
 public void onClick(View widget) { /* do something */ }
mySpannable.setSpan(myClickableSpan, i1, i2 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

If you wanted the clickable part of your TextView to open up a url by means of a WebViewActivity, for example, you would put the following code in the ClickableSpan.onClick method:

Intent i = new Intent(MyActivity.this, WebViewActivity.class);
i.putExtra("url", getResources().getString(R.string.myurl));


Muhammad said...

Hello there, great post! Very helpful. I have a question on extending this functionality. How would you adapt this to using a TextView that already exists and looking for a specific char sequence instead of the square brackets? For example setting the clickable span to be "world" from "Hello world"?

Thanks for any help.

adil said...

Not sure I understand you exactly but why not just use the String.indexOf(String) method as follows:

String myString = "Hello world";
int i1 = myString.indexOf("world");
int i2 = i1 + "world".length();

Yasen said...

Very nice, thanks!

Anonymous said...


siva ramakrishna kv said...

Great tutorial, but it setMovementmethod disabling the onLongclicklistener of textview and i m not able to get those action item on longpress of textview. Any solution for this?

Anonymous said...

Thank you very much. Your blog gave me the clue I needed:) Merry Christmas

Binh Nguyen said...

Thank you! That was very useful!

Anonymous said...

copied from stackoverflow. be real man

adil said...

Anonymous, you're right: sloppy of me not to include references. Thanks for pointing out MAN.