Android active link of url in TextView

Viewed 102929

I have getting dynamic text from a web service and showing the same in a TextView. Sometimes the TextView has url like <a href="http://hello.com">hello</a>. I have set the text using the following code.

textView.setText(Html.fromHtml(sampletext));

And also set android:autoLink="web" in the corresponding xml of that contains the TextView. Now the link is showing properly with blue color and underline, but I found the its just a dead link. Nothing is happening if we try to click it. What I have to do to make the link active?

10 Answers

If you are displaying in textview the string from strings.xml, strings containing the web link should not have word "a href=". If these words are deleted from the strings.xml file then the link will work.

Add these lines of code to your textView in xml File it will work perfectly fine..

android:autoLink="web" android:textColorLink="@android:color/holo_orange_dark" android:linksClickable="true"

or if want a your own link in textview add these lines of code in your java file

  final SpannableString s = new SpannableString("https://play.google.com/store/apps/details?id=cn.wps.moffice_eng");
  Linkify.addLinks(s, Linkify.ALL);

set this 's' String in your TextView by function

Textview.setText(s);

and don't forget to add this line

 ((TextView)findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());

id will be your textview id

Enjoy ...

Answer is right, BUT not complete, because I had in my xml some properties from other answers like autoLink and linksClickable and programatic way did not work. Also when I passes string with html from string resource also it did not work, so beware, you have to clean your xml and pass string directly exactly as in that answer.

    String text = "click on <a href=\"http://hello.com\">hello</a>";
    TextView textView = view.findViewById(R.id.textView);
    textView.setText(Html.fromHtml(text));
    textView.setMovementMethod(LinkMovementMethod.getInstance());

I did not try it without without LinkMovementMethod but now I am ok as it finally work. Other answers did not work for me or was for visible url text, not clickable text as link.

Related