Android
TextView
Clickable Links
Mobile Development
Android Programming

How to make links in a TextView clickable

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Making links clickable in a TextView is a common requirement when developing Android applications. This capability enhances user interaction by allowing users to directly access URLs, email addresses, phone numbers, or any other link types embedded within the text. Implementing clickable links in a TextView is straightforward but does require understanding how to handle text formatting and event handling in Android. This article discusses various methodologies to achieve clickable links using pure HTML or LinkMovementMethod and SpannableString.

The simplest way to make links clickable in a TextView is to use the autoLink attribute in your XML layout file. This approach can automatically detect URLs, phone numbers, email addresses, and map addresses, transforming them into clickable links.

xml
1<TextView
2    android:id="@+id/textView"
3    android:layout_width="wrap_content"
4    android:layout_height="wrap_content"
5    android:autoLink="web|email"
6    android:text="Visit our website at https://www.example.com or email us at [email protected]." />

The autoLink attribute can take the following options:

  • web: Links to URLs.
  • email: Links to email addresses.
  • phone: Links to phone numbers.
  • map: Links to map addresses.

2. Programmatically Using Linkify

Linkify is a flexible utility class that can be employed to create clickable links from plain text programmatically. This allows more customized control over the types of links you wish to make clickable.

Sample Code

java
TextView textView = findViewById(R.id.textView);
textView.setText("Visit https://www.example.com or call +1234567890");
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);

3. Using Html.fromHtml()

Android's Html.fromHtml() function permits the inclusion of HTML formatting in a TextView. This includes rendering links as clickable, though the method is more suited for static HTML content.

Sample Code

java
1TextView textView = findViewById(R.id.textView);
2String html = "Visit our <a href=\"https://www.example.com\">website</a> now!";
3textView.setText(Html.fromHtml(html));
4textView.setMovementMethod(LinkMovementMethod.getInstance());

Note

Html.fromHtml() is deprecated in API level 24, replaced by two overloads: Html.fromHtml(String, int) and Html.fromHtml(String, int, Html.ImageGetter, Html.TagHandler).

4. Using SpannableString

For dynamic or application-generated content, SpannableString offers the most flexibility. It allows developers to apply styles like links, fonts, and colors programmatically.

Sample Code

java
1TextView textView = findViewById(R.id.textView);
2SpannableString spannable = new SpannableString("Visit https://www.example.com now!");
3
4ClickableSpan clickableSpan = new ClickableSpan() {
5    @Override
6    public void onClick(View textView) {
7        // Handle the click event
8        Uri uri = Uri.parse("https://www.example.com");
9        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
10        textView.getContext().startActivity(intent);
11    }
12    @Override
13    public void updateDrawState(TextPaint ds) {
14        super.updateDrawState(ds);
15        ds.setUnderlineText(true); // Optional to update link styling
16    }
17};
18
19spannable.setSpan(clickableSpan, 6, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
20textView.setText(spannable);
21textView.setMovementMethod(LinkMovementMethod.getInstance());

Summary Table

MethodDescriptionProsCons
autoLinkXML attribute to auto-detect linksSimple to implementLimited to predefined link types
LinkifyUtility class for programmatic controlFlexible with link typesDefaults styles not customizable
Html.fromHtml()Parses HTML strings for displayLeverages HTML formattingLimited to static content
SpannableStringBuilds text with dynamic stylesFully customizableRequires more coding effort

Additional Considerations

  • Security and Permissions: When dealing with links that open external resources, ensure your app handles external URIs securely to prevent unwanted behavior. For instance, opening links in a web browser rather than directly within the app can avoid security risks.
  • User Experience: Always provide visual feedback that a piece of text is interactive. Underlining links or changing their color can significantly enhance the user experience.
  • Performance: For large texts with many links, consider efficiency. While SpannableString provides ultimate control, it might add overhead compared to simpler methods like autoLink.

These strategies provide a comprehensive guide to embedding clickable links in Android's TextView, enhancing interactivity within applications. Select the approach that best fits the specific requirements and architecture of your app.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.