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

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.

Approach:

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

    activity_main.xml

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

          
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        tools:context=".MainActivity">
      
        <TextView
            android:id="@+id/text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textAlignment="center"
            android:text="GeeksForGeeks A 
                    Computer Science Portal for Geeks"
            android:textSize="20sp"
            />
        <TextView
            android:id="@+id/text_view2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textAlignment="center"
            android:text="Learn Algorithm."
            android:textSize="20sp"
            />
    </LinearLayout>

    chevron_right

    
    

  2. Now add the following code in the MainActivity.java 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.

    MainActivity.java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package org.geeksforgeeks.gfgspannablestring;
      
    import android.graphics.Color;
    import android.os.Bundle;
    import android.text.SpannableString;
    import android.text.SpannableStringBuilder;
    import android.text.Spanned;
    import android.text.style.BackgroundColorSpan;
    import android.text.style.ForegroundColorSpan;
    import android.widget.TextView;
    import androidx.appcompat.app.AppCompatActivity;
      
    public class MainActivity extends AppCompatActivity {
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            TextView textView = findViewById(R.id.text_view);
            TextView textView2 = findViewById(R.id.text_view2);
      
            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
            spannableString.setSpan(green,
                                    0, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(cyan,
                                    40, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      
            spannableStringBuilder.setSpan(yellow,
                                           0, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      
            textView.setText(spannableString);
            textView2.setText(spannableStringBuilder);
        }
    }

    chevron_right

    
    

Output:

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.