Monday 16 October 2017

android - How to make links in a TextView clickable?

itemprop="text">

I have the following TextView defined:



            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">



where
@string/txtCredits is a string resource that contains
Link
text
.



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:



            name="txtCredits">            href="http://www.google.com">Google



But
this does:



            name="txtCredits">www.google.com


Which
is a bummer because I would much rather show a text link than show the full URL.


style="font-weight: bold;">

Answer




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




Link.java:




// text2 has links specified by putting 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.




android:id="@+id/text2"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/txtCredits"/>



That
solved it. Pretty difficult to uncover and
fix.



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



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...