我有以下TextView定义:
<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"/>
其中@string/txtCredits是一个字符串资源,包含<a href="some site">链接文本</a>。
Android正在突出显示TextView中的链接,但它们不响应单击。我做错了什么?我必须在我的活动中为TextView设置一个onClickListener像这样简单吗?
它看起来和我定义字符串资源的方式有关。
这行不通:
<string name="txtCredits"><a href="http://www.google.com">Google</a></string>
但这确实是:
<string name="txtCredits">www.google.com</string>
这是一个遗憾,因为我宁愿显示一个文本链接,而不是显示完整的URL。
在API演示中,我找到了问题的解决方案:
文件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上的大部分属性,以匹配演示中的内容。
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtCredits"/>
这就解决了问题。它很难发现和修复。
重要:不要忘记删除autoLink="web"如果你正在调用setMovementMethod()。
我注意到使用android:autoLink="web"因此
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="web"/>
对于url来说工作得很好,但是因为我有一个电子邮件地址和电话号码,我想要链接,我最终使用这一行android:autoLink="all"像这样
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="all"/>
而且效果很好。