将Web链接添加到TextView小部件

时间:2012-01-24 18:28:58

标签: android hyperlink textview

我想知道是否以及如何向TextView小部件添加Web链接。在我的应用程序中,我显示一些文本,并在此文本旁边添加一个图像。我想在文本中插入一个可点击的互联网链接。这可能吗?

3 个答案:

答案 0 :(得分:11)

您只需设置 android:autolink 属性。

<TextView
        android:autoLink="web"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"        
        android:text="http://www.google.com" />

答案 1 :(得分:0)

这就是我用代码

做的
private void setAsLink(TextView view, String url){
        Pattern pattern = Pattern.compile(url);
        Linkify.addLinks(view, pattern, "http://");
        view.setText(Html.fromHtml("<a href='http://"+url+"'>http://"+url+"</a>"));
    }

答案 2 :(得分:0)

如果您的网络链接与您在TextView中显示的文字不同:

布局文件中的TextView:

<TextView
    android:id="@+id/textview_with_hidden_clickable_link"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/string_with_text_and_link"/>

资源文件中的字符串:

<string name="string_with_text_and_link">
    <a href="http://any_web_site">The text in your TextView</a>
</string>

在你的Java类中:

((TextView)findViewById(R.id.textview_with_hidden_clickable_link))
    .setMovementMethod(LinkMovementMethod.getInstance());
  

注意:字符串资源中的http://是必需的。