Text Styling With Spans in Android


Introduction

When it comes to text formatting and styling in Android, Spannable strings offer a powerful, flexible approach that goes beyond what can be achieved with simple TextViews. From changing the text color to adding clickable links or even custom fonts, Spannable strings provide a myriad of possibilities. In this guide, we'll explore how to use spans to style text in your Android applications.

Understanding Spans

In Android, a "span" refers to a way to style text at a character or paragraph level by attaching one or more markup objects to a range of text. The Android framework offers several built-in span types in the android.text.style package, allowing you to style text in various ways.

How to Use Spans in Android?

Creating a Spannable String

Before applying spans, you need to create a SpannableString or SpannableStringBuilder object. Here's how to create a SpannableString −

String originalText = "Hello, Android Developers!";
SpannableString spannableString = new SpannableString(originalText);

Applying Spans

To apply a span, you use the setSpan() method, specifying the type of span, the start and end indices of the text to span, and a flag determining the behavior of the span −

ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(colorSpan, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

In this example, we're applying a ForegroundColorSpan to the first five characters of our string, effectively changing the color of the word "Hello" to red.

Exploring Different Span Types

Android offers a variety of spans that can be used to style or format text −

ForegroundColorSpan and BackgroundColorSpan − These spans change the color of the text and the background of the text, respectively.

  • AbsoluteSizeSpan − This span changes the text size to a specified absolute value.

  • RelativeSizeSpan − This span changes the text size to a proportion of the current size.

  • StyleSpan − This span applies a style to the text, such as bold or italic.

  • UnderlineSpan and StrikethroughSpan − These spans add an underline or strikethrough to the text, respectively.

  • URLSpan − This span transforms the text into a clickable link.

  • ClickableSpan − This abstract span must be overridden to make a portion of the text clickable, with a custom action defined in the onClick method.

Here's an example demonstrating multiple spans −

String originalText = "Hello, Android Developers!";
SpannableString spannableString = new SpannableString(originalText);

// Change "Hello" to red
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(colorSpan, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// Change "Android" to bold
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
spannableString.setSpan(boldSpan, 7, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// Add a clickable link to "Developers"
ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(@NonNull View widget) {
        // Handle click here
    }
};
spannableString.setSpan(clickableSpan, 15, 26, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// Set the styled text to a TextView
TextView textView = findViewById(R.id.textView);
textView.setText(spannableString);
textView.setMovementMethod(LinkMovementMethod.getInstance());

In this example, we're applying multiple spans to different parts of the string. We're coloring the word "Hello" in red, making "Android" bold, and turning "Developers" into a clickable span that triggers a custom action when clicked.

Remember to set the LinkMovementMethod instance to the TextView. This step is crucial when you have a ClickableSpan or URLSpan in your text, as it enables the text's click events.

Custom Spans

Beyond the built-in spans, Android also allows you to create custom spans. For example, you can create a custom span that changes the typeface of the text to a custom font −

public class CustomTypefaceSpan extends MetricAffectingSpan {
   private final Typeface typeface;

   public CustomTypefaceSpan(Typeface typeface) {
       this.typeface = typeface;
   }

   @Override
   public void updateMeasureState(@NonNull TextPaint textPaint) {
       textPaint.setTypeface(typeface);
       textPaint.setFlags(textPaint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
   }

   @Override
   public void updateDrawState(TextPaint textPaint) {
       textPaint.setTypeface(typeface);
       textPaint.setFlags(textPaint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
   }
}

In this class, we override the updateMeasureState and updateDrawState methods to apply the custom typeface to the text.

Best Practices for Using Spans

  • Reuse Spannable instances − If you're changing spans often (e.g., highlighting a text search in a large text view), it might be beneficial to reuse a SpannableStringBuilder instance rather than creating a new SpannableString each time.

  • Avoid overuse − Spans provide a lot of power, but with power comes responsibility. Overusing spans can lead to complex code and potential performance issues.

  • Use the right flags − The flags passed to the setSpan method can significantly affect the behavior of your spans, especially when the text is edited. Make sure you understand what each flag does.

Conclusion

Styling text with spans in Android is a versatile and powerful way to enhance the visual appearance and interactivity of your application's text content. While Android provides several built-in span types for common styling and formatting needs, the ability to create custom spans offers virtually unlimited possibilities for text customization.

Updated on: 19-Jun-2023

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements