HTML Formatting in TextView: Kotlin XML Android Guide

In Android development using Kotlin and XML layouts, the TextView is a fundamental UI element for displaying text. While simple text is straightforward, sometimes you need to format the text to include styles like bold, italics, different colors, or even clickable links. HTML formatting provides a convenient way to achieve this directly within the TextView. This article will explore how to effectively use HTML formatting in TextView in Kotlin XML development.

Why Use HTML Formatting in TextView?

  • Rich Text Display: Allows displaying text with different styles (bold, italic, underline) within the same TextView.
  • Flexibility: Supports various HTML tags for formatting text.
  • Dynamic Styling: Can be dynamically set in the Kotlin code, allowing for runtime text formatting.
  • Concise Code: Simplifies complex text formatting scenarios compared to manual manipulation.

Basic HTML Formatting in TextView

To enable HTML formatting in a TextView, you need to use the HtmlCompat.fromHtml() method from the androidx.core:core-ktx library. Let’s walk through the steps.

Step 1: Add the Dependency

Ensure you have the androidx.core:core-ktx dependency in your build.gradle file:


dependencies {
    implementation "androidx.core:core-ktx:1.9.0"
}

Make sure to sync your project after adding the dependency.

Step 2: XML Layout Setup

In your XML layout file, add a TextView element:


<TextView
    android:id="@+id/formattedTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:padding="16dp" />

Step 3: Kotlin Code to Apply HTML Formatting

In your Kotlin activity or fragment, use the HtmlCompat.fromHtml() method to apply HTML formatting to the TextView:


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.core.text.HtmlCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val formattedTextView: TextView = findViewById(R.id.formattedTextView)

        val htmlText = """
            <p>This is a <b>bold</b> text example.</p>
            <p>Here is some <i>italic</i> text.</p>
            <p>You can also <u>underline</u> text.</p>
            <p>And use different <font color='red'>colors</font>.</p>
        """

        formattedTextView.text = HtmlCompat.fromHtml(htmlText, HtmlCompat.FROM_HTML_MODE_LEGACY)
    }
}

Explanation:

  • The htmlText variable holds the HTML formatted string.
  • HtmlCompat.fromHtml() converts the HTML string into a Spanned object, which can be displayed in the TextView.
  • The HtmlCompat.FROM_HTML_MODE_LEGACY flag is used for compatibility with older Android versions.

Supported HTML Tags

Here are some commonly supported HTML tags that you can use in TextView:

  • <b>: Bold text
  • <i>: Italic text
  • <u>: Underlined text
  • <strong>: Strong text (usually displayed as bold)
  • <em>: Emphasized text (usually displayed as italic)
  • <font color='color_name'>: Text with specified color
  • <a href='url'>: Hyperlink
  • <ul>, <ol>, <li>: Unordered and ordered lists with list items
  • <p>: Paragraph
  • <br>: Line break

Example: Using Hyperlinks

Hyperlinks can be added using the <a> tag. Here’s an example:


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.core.text.HtmlCompat
import android.text.method.LinkMovementMethod

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val linkedTextView: TextView = findViewById(R.id.formattedTextView)

        val htmlLinkText = """
            <p>Visit our <a href='https://www.example.com'>website</a> for more information.</p>
        """

        linkedTextView.text = HtmlCompat.fromHtml(htmlLinkText, HtmlCompat.FROM_HTML_MODE_LEGACY)
        linkedTextView.movementMethod = LinkMovementMethod.getInstance()
    }
}

Key points:

  • <a href='https://www.example.com'>website</a> creates a hyperlink to https://www.example.com with the text “website”.
  • linkedTextView.movementMethod = LinkMovementMethod.getInstance() is crucial to enable the link to be clickable. Without it, the link will appear but won’t respond to touch events.

Using HTML Entities

Sometimes you need to display characters that have special meanings in HTML, such as <, >, or &. Use HTML entities to represent these characters:

  • &lt;: Less than (<)
  • &gt;: Greater than (>)
  • &amp;: Ampersand (&)
  • &quot;: Double quote (“)
  • &apos;: Single quote (‘)

Example:


val htmlText = "<p>10 &lt; 20</p>"
formattedTextView.text = HtmlCompat.fromHtml(htmlText, HtmlCompat.FROM_HTML_MODE_LEGACY)

This will display “10 < 20” in the TextView.

Dynamic HTML Formatting

You can dynamically format text in your Kotlin code based on certain conditions or data. Here’s an example:


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.core.text.HtmlCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val dynamicTextView: TextView = findViewById(R.id.formattedTextView)
        val condition = true
        val textToFormat = "Dynamic Text"

        val htmlText = if (condition) {
            "<b>$textToFormat</b>"
        } else {
            "<i>$textToFormat</i>"
        }

        dynamicTextView.text = HtmlCompat.fromHtml(htmlText, HtmlCompat.FROM_HTML_MODE_LEGACY)
    }
}

In this example, if the condition is true, the text will be bold; otherwise, it will be italic.

Advanced Techniques

Using CSS Styles

You can include basic CSS styles using the <style> tag within your HTML. However, note that the support for CSS is limited. It’s mainly useful for simple styling like colors and font sizes.


val htmlText = """
    <style>
        .highlight {
            color: blue;
            font-size: 18px;
        }
    </style>
    <p>This is <span class='highlight'>highlighted</span> text.</p>
"""
formattedTextView.text = HtmlCompat.fromHtml(htmlText, HtmlCompat.FROM_HTML_MODE_LEGACY)

Handling Clickable Spans

For more complex interactions like clickable sections with specific actions, you might need to use ClickableSpan. Here’s an example that combines HTML formatting with a clickable span:


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val clickableTextView: TextView = findViewById(R.id.formattedTextView)
        val fullText = "Click the link in this text"
        val linkText = "link"

        val spannableString = SpannableString(fullText)
        val startIndex = fullText.indexOf(linkText)
        val endIndex = startIndex + linkText.length

        val clickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                Toast.makeText(this@MainActivity, "Link clicked!", Toast.LENGTH_SHORT).show()
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.isUnderlineText = true
            }
        }

        spannableString.setSpan(clickableSpan, startIndex, endIndex, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE)
        clickableTextView.text = spannableString
        clickableTextView.movementMethod = LinkMovementMethod.getInstance()
    }
}

Key aspects:

  • Create a SpannableString to apply the clickable span.
  • Create a ClickableSpan to handle the click action.
  • Set the ClickableSpan on the specific part of the text.
  • Ensure the movementMethod is set to LinkMovementMethod.getInstance() for handling click events.

Best Practices

  • Keep It Simple: Use HTML formatting for basic text styles. For complex formatting, consider custom views or more advanced text styling techniques.
  • Performance: Avoid excessive HTML formatting in long texts, as it can impact performance.
  • Accessibility: Ensure that the formatting enhances readability and accessibility for all users.
  • Test Thoroughly: Test on different devices and Android versions to ensure consistent rendering.

Conclusion

HTML formatting in TextView offers a convenient and flexible way to style text in Android applications. By using the HtmlCompat.fromHtml() method, you can easily apply various styles, including bold, italics, colors, and hyperlinks. Whether you need simple text formatting or dynamic styling based on runtime conditions, understanding how to use HTML in TextView is a valuable skill for any Android developer. By following the guidelines and best practices outlined in this article, you can effectively enhance the visual appeal and user experience of your Android apps.