如何使 TextView 中的链接可点击 [英] How to make links in a TextView clickable

查看:52
本文介绍了如何使 TextView 中的链接可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下 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 是包含 Link text 的字符串资源.

where @string/txtCredits is a string resource that contains <a href="some site">Link text</a>.

Android 正在突出显示 TextView 中的链接,但它们不响应点击.我究竟做错了什么?我是否必须为我的 Activity 中的 TextView 设置一个 onClickListener 来实现这样简单的操作?

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.

这不起作用:

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

    // 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. It is pretty difficult to uncover and fix.

重要:如果您正在调用 setMovementMethod(),请不要忘记删除 autoLink=web".

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

这篇关于如何使 TextView 中的链接可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆