如何使TextView中的链接可点击? [英] How to make links in a TextView clickable?
问题描述
我定义了以下TextView:
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>
其中@string/txtCredits
是包含<a href="some site">Link text</a>
的字符串资源.
where @string/txtCredits
is a string resource that contains <a href="some site">Link text</a>
.
Android突出显示了TextView中的链接,但它们不响应点击.有人可以告诉我我在做什么错吗?我是否需要在活动中为TextView设置onClickListener,就像这样简单?
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>
但是确实如此:
<string name="txtCredits">www.google.com</string>
这真是令人讨厌,因为我宁愿显示文本链接,也不显示完整的URL.
Which is a bummer because I would much rather show a text link than show the full URL.
推荐答案
内置于API演示中,我找到了解决问题的方法:
Buried in the API demos I found the solution to my problem:
Link.java:
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());
我删除了TextView上的大多数属性,以使其与演示中的内容保持一致.
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. Pretty difficult to uncover and fix.
重要:如果您要呼叫setMovementMethod()
,请不要忘记删除autoLink="web"
.
Important: Don't forget to remove autoLink="web"
if you are calling setMovementMethod()
.
这篇关于如何使TextView中的链接可点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!