Support multiple links in a single string of text

You can support multiple links in a single string of text to perform different actions when clicking a subsection of text.

Version compatibility

This implementation requires that your project minSDK be set to API level 21 or higher.

Dependencies

This snippet embeds multiple clickable links into a single string of text:

Key points about the code

  • Uses the buildAnnotatedString function to create an annotated string of text.
  • Uses the pushStringAnnotation() method to begin annotating the upcoming text with any necessary information, such as a URL string.
  • Adds text using append(), and then uses the pop() method to halt the text annotation.
  • To add more links, repeat the previous two steps by surrounding each link with the pushStringAnnotation() and pop() methods. This annotates the text handled by the onClick event.
  • Creates a ClickableText component and uses the onClick parameter to manage user taps. Verify if there is a URL annotation linked to the text where you clicked. Then you can perform the click actions.

Results

One text string containing two different links
Figure 1. A screenshot of one text string containing two different links.

Parent collections

Text is a central piece of any UI. Find out different ways you can present text in your app to provide a delightful user experience.

Have questions or feedback

Go to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts.