Add links to a TextView in Android

Maybe you need to add links to a TextView on Android but you don’t want to use Linkify for some reasons and you also want that link to be opened when the user taps it.

Here is a simple solution:

yourTextView.setText(Html.fromHtml(
            "Text with a " +
            "<a href=\"http://www.myandroidsolutions.com/\">link to My Android Solutions</a> "));

// this is important as well !!
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());

Note that I used the fromHtml() method from the Html class to generate a Spanned object that maps the given Html string into something that the TextView will know how to display.

You can use that to add other Html styles to your text when you display it in a TextView but you need to make sure you know the supported tags.

I extracted the supported tags from the source code ad you can find those below.

Supported HTML tags by the Html Android class:

– br
– p
– div
– em
– b
– strong
– cite
– dfn
– i
– big
– small
– font
– blockquote
– tt
– a
– u
– sup
– sub
– h (1 to 6)
– img

Source here.

 

 

 

sponsored
Exit mobile version