Mobile Development 10 min read

Implementing an Expandable TextView with Topic and URL Span Handling in Android

This article demonstrates how to build a custom Android TextView that supports clickable topic spans, URL interception, and smooth expand‑collapse behavior using StaticLayout measurements, custom ButtonSpan labels, and optional height‑animation, providing a reusable solution for rich mobile text displays.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Implementing an Expandable TextView with Topic and URL Span Handling in Android

The article explains how to create a custom ExpandableTextView in Android that can display topics and other rich text elements as clickable spans.

It introduces a method replaceTopicSpan(List topics, String content, OnTopicClickListener listener) that iterates over topic data, finds start and end positions, and uses a SpanUtils helper to convert plain text into colored, clickable spans, returning the processed CharSequence.

The core click handling is implemented with a ClickableSpan that prevents rapid repeated clicks and invokes a callback when a topic is tapped.

For the expand/collapse functionality, the article describes using StaticLayout to measure line counts and determine where to truncate the text, then appends a "[More]" or "[Show Less]" label as a ButtonSpan . The setCloseText method calculates the required heights, creates the collapsed and expanded layouts, and sets the appropriate text and movement method.

Two approaches for toggling the view are presented: directly changing maxLines or animating the height change with a custom ExpandCollapseAnimation class that interpolates between the collapsed and expanded heights.

Additional utilities include replacing default URLSpan objects with a custom InterceptUrlSpan to handle link clicks inside the app, and configuring custom fonts via MyTypefaceSpan .

Finally, the article provides sample usage snippets and notes on integrating the component into a RecyclerView item, emphasizing the modularity of the solution.

Mobile DevelopmentanimationAndroidTextViewSpanexpandable
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.