Implementing Bold Text for Specific Parts in Android TextView

Nov 21, 2025 · Programming · 10 views · 7.8

Keywords: Android Development | TextView | Text Styling | Bold Text | SpannableStringBuilder | HTML Formatting

Abstract: This technical paper comprehensively explores methods for applying bold styling to specific text segments within Android TextView components. Through detailed analysis of HTML markup, SpannableStringBuilder, and Kotlin extension functions, the paper examines implementation principles, performance characteristics, and appropriate use cases. Complete code examples and implementation guidelines are provided to assist developers in selecting optimal solutions based on project requirements.

Introduction

In Android application development, TextView stands as one of the most frequently used UI components for displaying textual content. However, developers often encounter scenarios requiring different styling for specific text segments, such as bolding certain keywords. This requirement proves particularly common when displaying database query results or highlighting crucial information.

Problem Analysis

Developers frequently face situations where partial text within TextView requires bold formatting. For instance, after retrieving user ID and name from a database, there might be a need to display the ID portion in bold while maintaining normal styling for the name. Traditional setText() methods only support uniform text styling, failing to address this partial text formatting requirement.

HTML Markup Approach

Utilizing HTML markup represents the most straightforward method for implementing partial text formatting. Android provides the Html.fromHtml() method, which parses HTML-tagged strings and applies them to TextView components.

Implementation code example:

String id = "1111";
String name = "neil";
String sourceString = "<b>" + id + "</b> " + name;
txtResult.setText(Html.fromHtml(sourceString));

The core principle of this approach involves using HTML's <b> tag to define bold text. When invoking Html.fromHtml(), the system parses HTML markup and creates corresponding Spanned objects containing formatting information.

Advantages:

Disadvantages:

SpannableStringBuilder Method

For scenarios demanding higher performance and finer control, SpannableStringBuilder represents the recommended native Android text formatting solution, applying styles directly at character level.

Basic implementation code:

String id = "1111";
String name = "neil";
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(id);
builder.append(" ");
builder.append(name);

// Apply bold style to ID portion
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
builder.setSpan(boldSpan, 0, id.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

txtResult.setText(builder);

The crucial aspect of this method lies in the setSpan() method, which accepts four parameters:

Advantages:

Disadvantages:

Kotlin Extension Functions Approach

For teams employing Kotlin for Android development, extension functions provided by the android-ktx library offer significant code simplification.

Implementation code example:

val id = "1111"
val name = "neil"
val s = SpannableStringBuilder()
    .bold { append(id) }
    .append(" ")
    .append(name)
txtResult.setText(s)

Key advantages of this approach:

The android-ktx library provides additional useful extension functions:

// Set blue text
.color(blueColor) { append("blue text") }

// Set italic text
.italic { append("italic text") }

// Combine styles
.bold { italic { append("bold italic text") } }

Performance Comparison and Selection Guidelines

Practical development requires consideration of multiple factors when selecting appropriate methods:

HTML Markup Approach suitable for:

SpannableStringBuilder Method suitable for:

Kotlin Extension Functions Approach suitable for:

Best Practices

Real-world projects should adhere to the following best practices:

1. Style Reusability: Create style constants or utility classes for frequently used styles:

public class TextStyleUtils {
    public static final StyleSpan BOLD_STYLE = new StyleSpan(Typeface.BOLD);
    public static final StyleSpan ITALIC_STYLE = new StyleSpan(Typeface.ITALIC);
}

2. Position Calculation Optimization: Employ helper methods for dynamic text position calculation:

private int calculateBoldStart(String fullText, String boldPart) {
    return fullText.indexOf(boldPart);
}

private int calculateBoldEnd(String fullText, String boldPart) {
    return calculateBoldStart(fullText, boldPart) + boldPart.length();
}

3. Performance Monitoring: Monitor text rendering performance in sensitive scenarios:

long startTime = System.currentTimeMillis();
// Apply text styling
txtResult.setText(formattedText);
long endTime = System.currentTimeMillis();
Log.d("Performance", "Text styling took: " + (endTime - startTime) + "ms");

Compatibility Considerations

Different Android versions exhibit varying support for text styling features:

Android 4.0+: Full support for all methods

Android 8.0+: Html.fromHtml() behavior changes, recommend using Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY)

Android 10+: Enhanced support for custom fonts

Conclusion

Android development offers multiple approaches for applying bold styling to specific TextView text segments. The HTML markup method provides simplicity at the cost of performance; SpannableStringBuilder delivers excellent performance with increased complexity; Kotlin extension functions maintain performance while enhancing developer experience. Developers should select appropriate solutions based on specific project requirements, performance needs, and team technology stacks.

Regardless of chosen method, understanding underlying principles, properly handling text position calculations, and considering Android version compatibility remain crucial. Mastering these techniques enables developers to create both aesthetically pleasing and high-performance text display effects.

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.