Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make links in a TextView clickable

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. What am I doing wrong? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?

It 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.

like image 784
Richard Avatar asked Apr 29 '10 01:04

Richard


People also ask

Can I make a TextView clickable?

Just like Buttons and ImageViews we can add onClickListeners to TextViews by simply adding the attribute android:onClick="myMethod" to your TextView XML tag. The other way, TextView tv = (TextView) this.

How do you make a link clickable in a text file?

Select the text or picture that you want to display as a hyperlink. Press Ctrl+K. You can also right-click the text or picture and click Link on the shortcut menu. In the Insert Hyperlink box, type or paste your link in the Address box.


2 Answers

Buried in the API demos, I found the solution to my problem:

File Link.java:

    // text2 has links specified by putting <a> tags in the string     // resource.  By default these links will appear but not     // respond to user input.  To make them active, you need to     // call setMovementMethod() on the TextView object.      TextView t2 = (TextView) findViewById(R.id.text2);     t2.setMovementMethod(LinkMovementMethod.getInstance()); 

I removed most of the attributes on my TextView to match what was in the demo.

<TextView     android:id="@+id/text2"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="@string/txtCredits"/> 

That solved it. It is pretty difficult to uncover and fix.

Important: Don't forget to remove autoLink="web" if you are calling setMovementMethod().

like image 102
Richard Avatar answered Sep 23 '22 07:09

Richard


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.

like image 25
Janusz Avatar answered Sep 23 '22 07:09

Janusz