Handle links in a TextView

Various ways of using weblinks in a TextView.

Cheap ‘n easy

This stylizes the link, but does not make it clickable. You’ll need to set a click listener yourself.

<string name="text_with_links">Here is my link: https://pixplicity.com</string>
    android:autoLink="web" />

Properly show a link name instead of the full url, and open in the browser:

<string name="text_with_links">Here is <a href="https://pixplicity.com">my link</a></string>

Make sure to not use the autoLink attribute in combination with setMoveMethod.

Handle tap actions yourself

This snippet shows underlined clickable links in a TextView and prevents it from launching the default browser. Instead, you can take any other when the user taps your links.

<string name="text_with_links"><![CDATA[
    Here are my link: <u>one</u> and <u>two</u>.
val text = Html.fromHtml(getString(R.string.text_with_links))!!
val strBuilder = SpannableStringBuilder(text)
val underlines = strBuilder.getSpans(0, text.lastIndex, UnderlineSpan::class.java)

// Add an underlines Span for each link:
underlines.forEachIndexed { i, span ->
    val start = strBuilder.getSpanStart(span)
    val end = strBuilder.getSpanEnd(span)
    val flags = strBuilder.getSpanFlags(span)
    val launcher = object : ClickableSpan() {
        override fun onClick(view: View) {
        	// TODO configure your links here
            val url = when(i) {
            	0 -> BuildConfig.FIRST_LINK
            	1 -> BuildConfig.SECOND_LINK
        	// Launch the url, e.g.:
            // WebActivity.launch(this@MyActivity, url)
    strBuilder.setSpan(launcher, start, end, flags)

tv_link.text = strBuilder
tv_link.linksClickable = true
tv_link.movementMethod = LinkMovementMethod.getInstance()