我有以下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。


当前回答

这是一个非常单行的Android代码,使电话和URL可从textView中选择,无论字符串是什么,数据是什么。您不需要为此使用任何HTML标记。

TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText("some URL is www.google.com phone 7504567890 another URL lkgndflg.com ");

// Makes the textView's Phone and URL (hyperlink) select and go.
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);

其他回答

自动连接电话对我不起作用。下面的方法非常有效,

TextView tv = (TextView) findViewById(R.id.emergencynos);
String html2="<br><br>Fire - <b><a href=tel:997>997</a> </b></br></br>";
tv.append(Html.fromHtml(html2));
tv.setMovementMethod(LinkMovementMethod.getInstance());

我只使用android:autoLink=“web”,它工作得很好。单击该链接将打开浏览器并显示正确的页面。

我能猜到的一件事是,其他一些视图在链接的上方。透明的内容填充整个父元素,但不显示链接上方的任何内容。在这种情况下,点击指向这个视图而不是链接。

在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,可以点击与web的引用。URL被设置为这个TextView的文本。

例子:

 <TextView
    android:id="@+id/textViewWikiURL"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textStyle="bold"
    android:text="http://www.wikipedia.org/"
    android:autoLink="web" />

我注意到使用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"/>

而且效果很好。