How to link text in a TextView to open web URL

巧了我就是萌 提交于 2019-12-06 12:05:48
Jaison Brooks

I solved my problem simply by the following code.

  • 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" />`
    
  • Added the MovementMethod to the TextView:

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

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

This code was from vizZ answer at the following linked Question

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);

here is your 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;  
          }  

also create class 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);
    }
}

using this line you can also change the color of that text p_DrawState.setColor(R.color.info_text_color);

Add CDATA to your string resource

Strings.xml

<string name="urltext"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!