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


当前回答

你只需要在XML的文本视图中添加这个:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:autoLink="web"/>

其他回答

这是一个非常单行的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);

我不得不在几个地方寻找这个,但我最终得到了这个版本的代码。

文件strings.xml:

<string name="name1">&lt;a href="http://www.google.com">link text1&lt;/a></string>
<string name="name2">&lt;a href="http://www.google.com">link text2&lt;/a></string>

文件myactivity.xml:

<TextView
    android:id="@+id/textview1"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginTop="5dp" />

<TextView
    android:id="@+id/textview2"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginTop="5dp" />

文件myactivity .java(在onCreate()):

TextView tv1 = (TextView)findViewById(R.id.textview1);
TextView tv2 = (TextView)findViewById(R.id.textview2);

tv1.setText(Html.fromHtml(getResources().getString(R.string.name1)));
tv2.setText(Html.fromHtml(getResources().getString(R.string.name2)));
tv1.setMovementMethod(LinkMovementMethod.getInstance());
tv2.setMovementMethod(LinkMovementMethod.getInstance());

这将创建两个可点击的超链接,文本链接text1和链接text2将用户重定向到谷歌。

使用下面的代码:

String html = "<a href=\"http://yourdomain.com\">Your Domain Name</a>"
TextView textview = (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(LinkMovementMethod.getInstance());
textview.setText(Html.fromHtml(html));

将此添加到您的EditText:

android:autoLink="web"
android:linksClickable="true"

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

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