Open In App

How to change the Text Color of a Substring in android using SpannableString class?

Last Updated : 23 Feb, 2021
Like Article

In this article, we will learn about how to change the text color of a substring of a string. It is easy to change the color of the whole string but to change the color of a substring we have to use a special class SpannableString. But SpannableString class is not really helpful when it comes to change the background color of the text. So for that, we have to use SpannableStringBuilder class.


  1. Add the following code in activity_main.xml file. This will add two textviews in the activity_main layout.


    <?xml version="1.0" encoding="utf-8"?>
            android:text="GeeksForGeeks A 
                    Computer Science Portal for Geeks"
            android:text="Learn Algorithm."


  2. Now add the following code in the file. In this code we will change the color of substrings of first textview with SpannableString class and add a background color in second textview with SpannableStringBuilder. Create the objects of the classes with the texts you want to display and use setSpan function to change the color of the substring.

    package org.geeksforgeeks.gfgspannablestring;
    import android.os.Bundle;
    import android.text.SpannableString;
    import android.text.SpannableStringBuilder;
    import android.text.Spanned;
    import android.widget.TextView;
    public class MainActivity extends AppCompatActivity {
        protected void onCreate(Bundle savedInstanceState)
            TextView textView = findViewById(;
            TextView textView2 = findViewById(;
            String text = "GeeksForGeeks A Computer 
                           Science Portal for Geeks";
            String text2 = "Learn Algorithm.";
            SpannableString spannableString = new SpannableString(text);
            // we can only use backgroundcolor
            // span with a spannableStringBuilder.
            SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2);
            // It is used to set foreground color.
            ForegroundColorSpan green = new ForegroundColorSpan(Color.GREEN);
            ForegroundColorSpan cyan = new ForegroundColorSpan(Color.CYAN);
            // It is used to set background color.
            BackgroundColorSpan yellow = new BackgroundColorSpan(Color.YELLOW);
            // It is used to set the span to the string
                                    0, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    40, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                           0, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads