Java 如何链接TextView中的文本以打开web URL

Java 如何链接TextView中的文本以打开web URL,java,android,string,hyperlink,textview,Java,Android,String,Hyperlink,Textview,我花了一个多小时看了大量的例子,但没有一个能在TextView中将文本设置为链接到web URL 示例代码 text8 = (TextView) findViewById(R.id.textView4); text8.setMovementMethod(LinkMovementMethod.getInstance()); Strings.xml <string name="urltext"><a href="http://www.google.com">Google&

我花了一个多小时看了大量的例子,但没有一个能在TextView中将文本设置为链接到web URL

示例代码

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

 <string name="urltext"><a href="http://www.google.com">Google</a></string>
<string name="urltext"><![CDATA[<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”,但它没有超链接,单击后不会发生任何事情

我通过以下代码简单地解决了我的问题

  • 保留类似HTML的字符串:

     <string name="urltext"><a href="https://www.google.com/">Google</a></string>
    
现在它允许我点击超链接文本“谷歌”,现在打开网络浏览器

此代码来自以下链接的答案

还要创建类URLSpanNoUnderline.java

import co.questapp.quest.R;
import android.text.TextPaint;
import android.text.style.URLSpan;

public class URLSpanNoUnderline extends URLSpan {
    public URLSpanNoUnderline(String p_Url) {
        super(p_Url);
    }

    public void updateDrawState(TextPaint p_DrawState) {
        super.updateDrawState(p_DrawState);
        p_DrawState.setUnderlineText(false);
        p_DrawState.setColor(R.color.info_text_color);
    }
}

使用这一行,您还可以更改该文本的颜色
p\u DrawState.setColor(R.color.info\u text\u color)

将CDATA添加到字符串资源中

Strings.xml

 <string name="urltext"><a href="http://www.google.com">Google</a></string>
<string name="urltext"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>


AFAIK,
标签在字符串资源中不受支持,除非包装在
CDATA
中。您尝试过这个吗?@user1873880我尝试过这个,但它似乎不起作用。除非我有什么事missing@JaisonBrooks查看user1873880发布的链接中的答案,我认为您可能需要删除一些您设置的链接属性(如autoLink和linksClickable)。@JamesHolderness谢谢,事实上,我已经用那封邮件上的一个答案解决了这个问题。许多其他答案建议使用
Html.fromHtml
——当我删除它时,链接起作用了!谢谢
import co.questapp.quest.R;
import android.text.TextPaint;
import android.text.style.URLSpan;

public class URLSpanNoUnderline extends URLSpan {
    public URLSpanNoUnderline(String p_Url) {
        super(p_Url);
    }

    public void updateDrawState(TextPaint p_DrawState) {
        super.updateDrawState(p_DrawState);
        p_DrawState.setUnderlineText(false);
        p_DrawState.setColor(R.color.info_text_color);
    }
}
<string name="urltext"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>