3

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

示例代码!

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

字符串.xml

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

主要的.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”,但它没有超链接,点击后没有任何反应。

4

3 回答 3

8

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

  • 保留类似 HTML 的字符串:

     <string name="urltext"><a href="https://www.google.com/">Google</a></string>
    
  • 完全没有链接特定配置的布局:

     <TextView
        android:id="@+id/link"
        android:text="@string/urltext" />`
    
  • 在 TextView 中添加了 MovementMethod:

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

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

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

于 2013-07-27T23:12:42.773 回答
1
TextView text=(TextView) findViewById(R.id.text);   

    String value = "<html> click to go <font color=#757b86><b><a href=\"http://www.google.com\">google</a></b></font> </html>";
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);

于 2014-04-17T21:35:45.020 回答
-1

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

字符串.xml

<string name="urltext"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>
于 2015-02-17T11:19:54.110 回答