我有以下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应用程序中寻找文本和超链接组合的任何人。
在string.xml:
<string name="applink">Looking for Digital Visiting card?
<a href="https://play.google.com/store/apps/details?id=com.themarkwebs.govcard">Get it here</a>
</string>
现在你可以在任何给定的视图中使用这个字符串,就像这样:
<TextView
android:id="@+id/getapp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:textColor="@color/main_color_grey_600"
android:textSize="15sp"
android:text="@string/applink"/>
现在,在您的活动或片段中,执行以下操作:
TextView getapp =(TextView) findViewById(R.id.getapp);
getapp.setMovementMethod(LinkMovementMethod.getInstance());
到目前为止,你不需要设置android:autoLink="web"或android:linksClickable="true"使用这种方法。
在花了一段时间之后,我发现:
android:autoLink="web"工作,如果你有完整的链接在你的HTML。以下内容将以蓝色高亮显示,并可点击:
Some text <a href="http://www.google.com">http://www.google.com</a> .
一些文字http://www.google.com
view.setMovementMethod (LinkMovementMethod.getInstance ());将与以下工作(将突出显示和可点击):
Some text <a href="http://www.google.com">http://www.google.com</a> .
一些文字http://www.google.com
一些文本<a href="http://www.google.com">转到谷歌</a>
注意,第三个选项有一个超链接,但是链接的描述(标签之间的部分)本身并不是链接。android:autoLink="web"不工作与这样的链接。
android:autoLink="web"如果在XML中设置将覆盖view.setMovementMethod(LinkMovementMethod.getInstance());(即。第三类链接将被突出显示,但不能点击)。
这个故事的寓意是使用view.setMovementMethod(LinkMovementMethod.getInstance());在你的代码中,确保你没有android:autoLink="web"在你的XML布局中,如果你想要所有的链接都是可点击的。