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

时间:2013-07-27 22:55:14

标签: 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</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”,但它没有超链接,点击后也没有任何反应。

3 个答案:

答案 0 :(得分:6)

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

  • 保持类似HTML的字符串:

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

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

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

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

此代码来自以下链接vizZ

Question回答

答案 1 :(得分: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);

的颜色

答案 2 :(得分:-1)

将CDATA添加到字符串资源

的strings.xml

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