Android SpannableString Example

android.text.SpannableString is a character sequence type class. You can use it as a String object in android TextView. But SpannableString can make TextView content more colorful and diverse. This article will show you examples about how to use SpannableString with TextView.

1. Example Overview.

There are totally eleven Button and one TextView object in this example. When click each button, you can see the text in the textview changed accordingly. All the effect are implemented with android.text.SpannableString class.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/LBND_bek9C0

2. How To Use SpannableString.

Below is the steps to use android.text.SpannableString.

  1. Create a SpannableString object with a String object as input parameter.
    SpannableString spannableStr = new SpannableString("Hello SpannableString Example.");
  2. Create a span object that you want to apply to the string. Android provide below span class. ForegroundColorSpan, BackgroundColorSpan, UnderlineSpan, StrikethroughSpan, RelativeSizeSpan, StyleSpan, SuperscriptSpan, SubscriptSpan, ImageSpan, URLSpan, ClickableSpan etc.
    BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.GREEN);
  3. Invoke SpannableString’s setSpan(Object what, int start, int end, int flags) method to apply the span object to the string.
    what : is the span object created in step 2.
    start : The start character index in original string.
    end : The end character index in original string.
    flagsSpanned.SPAN_INCLUSIVE_EXCLUSIVE ( include start character and exclude end character), Spanned.SPAN_INCLUSIVE_INCLUSIVE ( include both start and end character), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ( exclude both start and end character), Spanned.SPAN_EXCLUSIVE_INCLUSIVE ( exclude start character and include end character)
    spannableStr.setSpan(backgroundColorSpan, 15, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
  4. Set the SpannableString object in textview use setText method.
    spannableTextView.setText(spannableStr)

3. SpannableStringActivity.java Source Code.

package com.dev2qa.example;

import android.app.AlertDialog;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.text.*;
import android.text.style.*;
import android.graphics.*;

public class SpannableStringActivity extends AppCompatActivity {

    private TextView spannableTextView;
    private String originalText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spannable_string);

        // First set this activity title.
        this.setTitle("Android SpannableString Example");

        // Get text in TextView object.
        spannableTextView = (TextView)findViewById(R.id.textViewSpannableString);
        originalText = (String)spannableTextView.getText();

        // Set specified text color to red.
        Button btnSetForegroundColor = (Button)findViewById(R.id.buttonSetForegroundColor);
        btnSetForegroundColor.setAllCaps(false);
        btnSetForegroundColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);
                spannableStr.setSpan(foregroundColorSpan, 15, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

        // Set specified text background color to green.
        Button btnSetBackgroundColor = (Button)findViewById(R.id.buttonSetBackgroundColor);
        btnSetBackgroundColor.setAllCaps(false);
        btnSetBackgroundColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);
                BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.GREEN);
                spannableStr.setSpan(backgroundColorSpan, 15, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

        // Add under line to specified text.
        Button btnSetUnderLine = (Button)findViewById(R.id.buttonSetUnderLine);
        btnSetUnderLine.setAllCaps(false);
        btnSetUnderLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);
                UnderlineSpan underlineSpan = new UnderlineSpan();
                spannableStr.setSpan(underlineSpan, 15, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

        // Add strike through line to specified text.
        Button btnSetStrikeThrough = (Button)findViewById(R.id.buttonSetStrikeThrough);
        btnSetStrikeThrough.setAllCaps(false);
        btnSetStrikeThrough.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);
                StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
                spannableStr.setSpan(strikethroughSpan, 15, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

        // Change specified text font size.
        Button btnSetRelativeSize = (Button)findViewById(R.id.buttonSetTextRelativeSize);
        btnSetRelativeSize.setAllCaps(false);
        btnSetRelativeSize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);

                RelativeSizeSpan relativeSizeSpan1 = new RelativeSizeSpan(1.2f);
                RelativeSizeSpan relativeSizeSpan2 = new RelativeSizeSpan(1.8f);
                RelativeSizeSpan relativeSizeSpan3 = new RelativeSizeSpan(2.6f);

                spannableStr.setSpan(relativeSizeSpan1, 15, 19, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableStr.setSpan(relativeSizeSpan2, 19, 24, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableStr.setSpan(relativeSizeSpan3, 24, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

        // Change specified text style.
        Button btnSetStyle = (Button)findViewById(R.id.buttonSetStyle);
        btnSetStyle.setAllCaps(false);
        btnSetStyle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);

                StyleSpan styleSpanBold  = new StyleSpan(Typeface.BOLD);
                StyleSpan styleSpanItalic  = new StyleSpan(Typeface.ITALIC);

                spannableStr.setSpan(styleSpanBold, 15, 19, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableStr.setSpan(styleSpanItalic, 19, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

                spannableTextView.setText(spannableStr);
            }
        });

        // Change specified text superscript.
        Button btnSetSuperscript = (Button)findViewById(R.id.buttonSetSuperscript);
        btnSetSuperscript.setAllCaps(false);
        btnSetSuperscript.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);
                SuperscriptSpan superscriptSpan = new SuperscriptSpan();
                spannableStr.setSpan(superscriptSpan, 15, 16, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

        // Change specified text subscript.
        Button btnSetSubScript = (Button)findViewById(R.id.buttonSetSubscript);
        btnSetSubScript.setAllCaps(false);
        btnSetSubScript.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);
                SubscriptSpan subscriptSpan = new SubscriptSpan();
                spannableStr.setSpan(subscriptSpan, 15, 16, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

        // Add images in text.
        Button btnSetSubImage = (Button)findViewById(R.id.buttonSetImage);
        btnSetSubImage.setAllCaps(false);
        btnSetSubImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);

                Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
                drawable.setBounds(0, 0, 100, 100);
                ImageSpan imageSpan = new ImageSpan(drawable);

                spannableStr.setSpan(imageSpan, 15, 19, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

        // Add URL in text.
        Button btnSetUrl = (Button)findViewById(R.id.buttonSetUrl);
        btnSetUrl.setAllCaps(false);
        btnSetUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);

                URLSpan urlSpan = new URLSpan("http://www.yahoo.com");

                spannableStr.setSpan(urlSpan, 15, 19, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

                spannableTextView.setMovementMethod(LinkMovementMethod.getInstance());
                spannableTextView.setText(spannableStr);
            }
        });

        // Add Clickable in text.
        Button btnSetClickable = (Button)findViewById(R.id.buttonSetClickable);
        btnSetClickable.setAllCaps(false);
        btnSetClickable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableString spannableStr = new SpannableString(originalText);

                ClickableSpan clickableSpan = new ClickableSpan() {
                    @Override
                    public void onClick(View view) {
                        AlertDialog dlg = new AlertDialog.Builder(SpannableStringActivity.this).create();
                        dlg.setMessage("You click the text.");
                        dlg.show();
                    }
                };

                spannableStr.setSpan(clickableSpan, 15, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableTextView.setText(spannableStr);
            }
        });

    }
}

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.