Skip to content
Related Articles

Related Articles

Improve Article

Text Styling With Spans in Android

  • Last Updated : 23 Feb, 2021
Geek Week

Spans are the markup objects. These can be used to style the texts at the character or paragraph level. Spans are attached to text objects and give us a variety of options to the text including adding color to text, applying clickable behavior to text, scaling text size, and drawing text in a customized way. Spans can also be used to change TextPaint properties, draw on Canvas, and even change the text layout. In order to use spans, we have to use one of the classes listed below.

Class

Mutable Text

Mutable Markup

Data Structure



SpannedStringNoNoLinear Array
SpannableStringNoYesLinear Array
SpannableStringBuilderYesYesInterval Tree

All these classes extend the Spanned interface. SpannableString and SpannableStringBuilder also extend the Spannable interface. In order to use a span, we need to call setSpan(Object spans, int start, int end, int flag) on the Spannable object. Object span parameter refers to the span to apply to the text, start and end refer to the indexes of the positions of text over which spans are to be applied. 

On applying span, if the inserted text is inside the span boundaries then the span automatically expend the inserted text And if the inserted text is in between start and end indices – the flag parameter will decide that span should include or exclude the inserted text. 

  • Spannable.SPAN_EXCLUSIVE_INCLUSIVE – Include inserted text
  • Spannable.SPAN_EXCLUSIVE_EXCLUSIVE – Exclude the inserted text.

Example

In this example, We are going to change the style of text by using the SpannableString class together with StyleSpan, UnderlineSpan, and StrikethroughSpan. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Text Styling With Spans In Android Sample Image

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

In the layout file, we will have a TextView. We will style this text using spans. Below is the code snippet for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--The text we provide here is only
        for reference purpose we need to
        provide it in MainActivity.java file-->
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I want Red and Green to be 
                      coloured and this to be Bold,
                      Italic and Underline and Strike-through"
        android:textAlignment="center"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  
</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Working with the MainActivity.java

In the MainActivity.java file, we will first define a string that needs to be styled. Once we define the string we convert it into a Spannable String after that we define all the spans that we need for modification and then we set these spans over the spannable strings and finally set the spannable string to TextView. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
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);
  
        // Referencing the TextView
        TextView textView = (TextView) findViewById(R.id.textView);
          
        // The text that need to be styled using spans
        String text = "I want Red and Green to be colored and these to be Bold, Italic and Underline and Strike-through";
          
        // This will convert the text-string to spannable string
        // and we will used this spannableString to put spans on 
        // them and make the sub-string changes
        SpannableString spannableString = new SpannableString(text);
          
        // Creating the spans to style the string
        ForegroundColorSpan foregroundColorSpanRed = new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan foregroundColorSpanGreen = new ForegroundColorSpan(Color.GREEN);
        StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
        StyleSpan italicSpan = new StyleSpan(Typeface.ITALIC);
        UnderlineSpan underlineSpan = new UnderlineSpan();
        StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
          
        // Setting the spans on spannable string
        spannableString.setSpan(foregroundColorSpanRed, 7, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(foregroundColorSpanGreen, 15, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(boldSpan, 51, 55, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(italicSpan, 57, 63, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(underlineSpan, 68, 77, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(strikethroughSpan, 82, 96, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
          
        // Setting the spannable string on TextView
        textView.setText(spannableString);
    }
}

Output: Run On Emulator

Text Styling With Spans In Android Sample Image

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :