Saturday 8 December 2012

make links in a Text-view clickable in Android

Android TextView and HTML



Recently I wanted to display a TextView with a clickable link.




Let's setup a simple TextView and add a link.

mTextSample = (TextView) findViewById(R.id.textSample);
String text = "Visit my blog jtomlinson.blogspot.com";
mTextSample.setText(text);

The result is pure text displayed on screen. Android has no idea we want to display a clickable link.

This wasn't acceptable. I wanted people to be able to launch the url directly by clicking on the link. The next step was to use Linkify, a great feature for adding clickable links to text.

mTextSample = (TextView) findViewById(R.id.textSample);
String text = "Visit my blog jtomlinson.blogspot.com";
mTextSample.setText(text);
//jmt: pattern we want to match and turn into a clickable link
Pattern pattern = Pattern.compile("jtomlinson.blogspot.com");
//jmt: prefix our pattern with http://
Linkify.addLinks(mTextSample, pattern, "http://");


Now we are getting somewhere. Our link is clickable and the user is taken directly to the url using the browser. This is the most basic example of Linkify.WikiNotes is an example from Google that discusses more detailed use of Linkify.

Our next step is to tidy up the view by removing the url and allow the user to click on "blog" to launch the browser.

mTextSample = (TextView) findViewById(R.id.textSample);
String text ="Visit my blog"
mTextSample.setText(text);

Note: blogspot has marked up my text string, you can see the actual string in the screen shot below.



Again this doesn't quite work straight away. We need to tweak our text slightly so Android understands we want to display HTML.

All we need to do is update our setText method to include Html.fromHtml. This method will style our text based on the HTML tags. Not all tags are included so make sure you test first.

//jmt: style our text based on html tags
mTextSample.setText(Html.fromHtml(text));



Perfect, now we have our TextView looking exactly how we want it. There is only one problem, if we try to click the link nothing happens.

We have one last line of code to write. This informs Android we have a link that we would like to open when selected.

mTextSample.setMovementMethod(LinkMovementMethod.getInstance());


When clicked, the browser is launched and the user is taken to the specified url.






Here are the 4 lines of code required to display a clickable link
mTextSample = (TextView) findViewById(R.id.textSample);
mTextSample.setMovementMethod(LinkMovementMethod.getInstance());
String text = "Visit my blog";
mTextSample.setText(Html.fromHtml(text));

1 comment:

  1. Appreciation to my father who informed me concerning this
    web site, this blog is actually awesome.

    ReplyDelete