Implementing Multi-Colored Text in Android TextView: HTML vs. SpannableString Approaches

Dec 05, 2025 · Programming · 13 views · 7.8

Keywords: Android | TextView | multi-colored text

Abstract: This paper explores two core methods for achieving multi-colored text in Android TextView. First, it details the technique of using HTML-formatted strings with the Html.fromHtml() method, which is the highest-rated solution on Stack Overflow. Second, as a supplement, it analyzes the alternative approach using SpannableString and ForegroundColorSpan, achieving color variation via append(). The article delves into principles, code implementation, comparative advantages and disadvantages, and application scenarios, assisting developers in selecting the appropriate solution based on their needs. All code examples are refactored and thoroughly annotated to ensure clarity and ease of understanding.

Introduction

In Android app development, TextView is a fundamental component for displaying text. Occasionally, developers need to show text in different colors within a single TextView to enhance visual effects or highlight key information. For instance, in chat applications, user messages and system prompts may use distinct colors; or in data displays, positive and negative values might be differentiated in red and green. Based on high-scoring Q&A data from Stack Overflow, this paper systematically examines two primary methods for achieving this functionality: HTML formatting and SpannableString application.

Implementing Multi-Colored Text Using HTML Formatting

The first method leverages HTML tags to define text colors, representing the most straightforward and widely adopted solution. Its core lies in converting a string containing HTML color tags into a Spanned object recognizable by Android. The implementation steps are as follows: First, construct a string where the portions to be colored are wrapped with <font color=#hexcode> tags. For example, to display "red text" and "yellow text", one might define the string as: <font color=#cc0029>red text</font> <font color=#ffcc00>yellow text</font>. Here, #cc0029 and #ffcc00 are hexadecimal color codes representing dark red and bright yellow, respectively.

Next, convert this string to a Spanned object using the Html.fromHtml() method. This method parses the HTML tags and generates corresponding styles. In Android, Html.fromHtml() is a static method of the android.text.Html class, supporting basic HTML tags such as <font>, <b>, etc. A code example is provided below:

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
textView.setText(Html.fromHtml(text));

In this example, the text variable stores the HTML-formatted string, Html.fromHtml(text) converts it to a Spanned object, which is then set to the TextView via setText(). This approach is simple and user-friendly, particularly suitable when text is pre-formatted as HTML from sources like networks or databases. However, it relies on HTML parsing, which may introduce performance overhead, and does not support all HTML tags, potentially limiting complex styling requirements.

Implementing Multi-Colored Text Using SpannableString

The second method employs SpannableString and ForegroundColorSpan, offering finer control over text styling. Unlike the HTML method, this approach operates directly in Java/Kotlin code, avoiding string parsing. Its core concept is "spans", which are styles applied to specific ranges of text. The implementation process involves: creating a SpannableString object, then attaching color spans using the setSpan() method.

For instance, to set a piece of text to blue, one might write the following code:

Spannable word = new SpannableString("Your message");
word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(word);

Here, new ForegroundColorSpan(Color.BLUE) creates a blue foreground color span, and the setSpan() method applies it to the text from index 0 to word.length() (i.e., the entire string). The parameter Spannable.SPAN_EXCLUSIVE_EXCLUSIVE specifies that the span is exclusive, meaning newly inserted text will not inherit this style.

For multi-colored text, multiple SpannableString objects can be concatenated using the append() method. Referencing the example from the Q&A:

Spannable wordTwo = new SpannableString("Your new message");
wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(wordTwo);

This code first sets a blue text, then appends a red text, thereby achieving a multi-colored effect in a single TextView. This method offers better performance and supports dynamic style adjustments, but the code is slightly more verbose, making it suitable for scenarios requiring complex interactions or real-time style updates.

Method Comparison and Selection Recommendations

Both methods have their strengths and weaknesses. The HTML method scores higher (10.0) due to its simplicity and compatibility with web content. It is ideal when text is pre-formatted as HTML, such as when fetched directly from API responses. However, it may parse slower and has limited style support. The SpannableString method scores lower (5.3) but provides more powerful control, such as mixing multiple spans (e.g., color, font, click events), making it suitable for high-performance or complex UI needs.

In practical development, it is recommended to choose based on specific scenarios: if the text is static and sourced as HTML, use the HTML method; if dynamic styling or performance optimization is needed, employ SpannableString. Additionally, note escaping issues: in HTML strings, special characters like < and > must be escaped as &lt; and &gt; to avoid parsing errors. For example, when displaying the <br> tag as text, it should be written as &lt;br&gt;.

Conclusion

To implement multi-colored text in Android TextView, developers can flexibly choose between HTML formatting or SpannableString methods. The former is based on standard web technologies and easy to integrate; the latter offers native control and better performance. By deeply understanding their principles and implementations, developers can effectively enhance the visual appeal of their application interfaces. In the future, with advancements in Android Jetpack components like TextViewCompat, text styling may become further simplified, but these methods remain core practices for now.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.