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

我花了一个多小时查看大量示例,但实际上没有一个能够在TextView中设置文本以链接到Web URL。

示例代码!

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

strings.xml中

  Google 

main.xml中

   

目前此代码将文本显示为“Google”,但它没有超链接,点击时没有任何反应。

我只是通过以下代码解决了我的问题。

  • 保持类似HTML的字符串:

      Google 
  • 根本没有链接特定配置的布局:

      ` 
  • 将MovementMethod添加到TextView:

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

现在,它允许我单击超链接文本“Google”,现在打开Web浏览器。

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

 TextView text=(TextView) findViewById(R.id.text); String value = " click to go google "; Spannable spannedText = (Spannable) Html.fromHtml(value); text.setMovementMethod(LinkMovementMethod.getInstance()); Spannable processedText = removeUnderlines(spannedText); text.setText(processedText); 

这是你的removeUnderlines()

 public static Spannable removeUnderlines(Spannable p_Text) { URLSpan[] spans = p_Text.getSpans(0, p_Text.length(), URLSpan.class); for (URLSpan span : spans) { int start = p_Text.getSpanStart(span); int end = p_Text.getSpanEnd(span); p_Text.removeSpan(span); span = new URLSpanNoUnderline(span.getURL()); p_Text.setSpan(span, start, end, 0); } return p_Text; } 

还创建类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_DrawState.setColor(R.color.info_text_color);

将CDATA添加到您的字符串资源

strings.xml中

 Google]]>