I have the following TextView defined:
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/txtCredits"
android:autoLink="web" android:id="@+id/infoTxtCredits"
android:layout_centerInParent="true"
android:linksClickable="true"></TextView>
where @string/txtCredits
is a string resource that contains <a href="some site">Link text</a>
.
Android is highlighting the links in the TextView, but they do not respond to clicks. Can someone tell me what I'm doing wrong? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?
Looks like it has to do with the way I define my string resource. This does not work:
<string name="txtCredits"><a href="http://www.google.com">Google</a></string>
But this does:
<string name="txtCredits">www.google.com</string>
Which is a bummer because I would much rather show a text link than show the full URL.
Only what do you need to add this in text view in xml
I noticed that using
android:autoLink="web"
thusworked OK for URLs but since I had an e-mail address and phone number that I wanted to link as well, I ended up using this line
android:autoLink="all"
like thisand it worked like a charm.
Add CDATA to your string resource
Strings.xml
I'm using only
android:autoLink="web"
and it works fine. A click on the link opens the browser and shows the correct page.One thing I could guess is that some other view is above the link. Something that is transparent fills the whole parent but don't displays anything above the link. In this case the click goes to this view instead of the link.
Richard, next time, you should add this code under TextView at the layout XML instead.
This should be like this.
You don't need to use this code (
t2.setMovementMethod(LinkMovementMethod.getInstance());
) in order to make the link clickable.Also, here's the truth: as long as you set the autoLink and the linksClickable, don't forget to add this at String.xml file so that the clickable link will work.
[Tested in Pre-lollipop as well as in Lollipop and above]
You can get your HTML string from the backend or from your resources files. If you put your text as an resource string, make sure to add the
CDATA
tag:Then in code you need to get the string and assign it as HTML and set a link movement method: