如何在TextView中链接文本以打开Web URL [英] How to link text in a TextView to open web URL

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

问题描述

我花了一个多小时来研究大量示例,但这些示例都无法在TextView中设置文本以链接到Web URL.

I've spent over an hour looking at plenty of examples and none of it actually works for setting text in a TextView to link to a web URL.

示例代码!

text8 = (TextView) findViewById(R.id.textView4);
text8.setMovementMethod(LinkMovementMethod.getInstance());

Strings.xml

Strings.xml

 <string name="urltext"><a href="http://www.google.com">Google</a></string>

main.xml

 <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autoLink="web"
        android:linksClickable="true"
        android:text="@string/urltext"
        android:textAppearance="?android:attr/textAppearanceMedium" />

当前,此代码将文本显示为"Google",但未超链接,单击后无任何反应.

Currently this code display the text as "Google" however its not hyperlinked and nothing happens upon clicking.

推荐答案

我仅通过以下代码解决了我的问题.

I solved my problem simply by the following code.

  • 保留类似HTML的字符串:

  • Kept HTML-like string:

 <string name="urltext"><a href="https://www.google.com/">Google</a></string>

  • 完全没有链接特定配置的布局:

  • Made layout with NO link-specific configuration at all:

     <TextView
        android:id="@+id/link"
        android:text="@string/urltext" />`
    

  • 将MovementMethod添加到TextView:

  • Added the MovementMethod to the TextView:

     mLink = (TextView) findViewById(R.id.link);
     if (mLink != null) {
       mLink.setMovementMethod(LinkMovementMethod.getInstance());
     }
    

  • 现在,它允许我单击超链接文本"Google",然后打开Web浏览器.

    Now it allows me to click the hyperlinked text "Google" and now opens web browser.

    此代码来自 vizZ 的答案,位于以下链接的

    This code was from vizZ answer at the following linked Question

    这篇关于如何在TextView中链接文本以打开Web URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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