Clickable text inside TextView – Android Programming


Make a particular text of a TextView clickable and change the color and style of the text.

We all know how to make a whole TextView clickable. But in this post, we are going to do something different. In this post, I am going to show you how to make a particular text of a TextView clickable.

We can’t achieve this just using the onClick method on the view. For this, Android provides us a class called SpannableString.

Now let’s make an example project to understand it better.We are going to make a project which will have two activities. The first activity will have just a TextView and clicking on a word the second activity will open. See the screenshot below –



Removing white screen when switching activities – Android

RecyclerView with CheckBoxes – Android

Toast message and positioning – Android

As you can understand from the above image, there will be a TextView with a text “Click HERE to go the next activity”. Tapping on HERE, the SecondActivity will open. We are also going to see how to change the color of the span of the text and how to remove the underline and change the style to bold.

Create a new project. Name it whatever you want.

Go to your activity_main.xml file and add a TextView like this –

Go to your class and update your version of the file with ours.

Now to make a particular text clickable, we will use the class SpannableString. Here we will also set the text of the TextView and change the color and style of the text which will be clickable.

Copy the below code and update your class.

In the above code, see how we are setting the text of the TextView. The SpannableString constructor accepts a CharSequence parameter. And this CharSequence parameter is our source text.

We are also overriding two methods, onClick and updateDrawState. The updateDrawState method is to update the appearance of the text, the text on which we want to set the click event.

By default, the setUnderlineText is set to true. If you want the underline, then you don’t need this line. With setColor, we are changing the color of the text.

Here we are setting the span on spannableString object. The first parameter is clickableSpan object, the second parameter is the starting index, the third one is the end index, and the fourth one is flag.

In the text “Click HERE to go the next activity” we want to set the click event on HERE. So ‘H‘ is at index 6 and 10 is the end index.

We are also changing the font style to bold like this –

Now run your project and click on the text to go the SecondActivity. That’s all.
Don’t forget to share your thoughts on this post in the comment section below.


You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *