简体   繁体   中英

how to create textview link without underscore in android

i came into this wired situation, my code is as follow

LinearLayout ll = new LinearLayout(this);
TextView tv = new TextView(this);
ll.addView(tv);
tv.setText(Html.fromHtml("<a STYLE=\"text-decoration:none;\" href=\"" 
        + StringEscapeUtils.escapeJava(elem.getChildText("newsLink")) + "\">" 
                + StringEscapeUtils.escapeJava(elem.getChildText("Title")) + "</a>"));
tv.setTextColor(Color.BLACK);

but the style="text-decoration:none" and tv.setTextColor(color.black) both not working, the link is still in blue with underscore, any hints on why they're not working? Thanks!

you can try this. such as

String content = "your <a href='http://some.url'>html</a> content";

Here is a concise way to remove underlines from hyperlinks:

Spannable s = (Spannable) Html.fromHtml(content);
for (URLSpan u: s.getSpans(0, s.length(), URLSpan.class)) {
    s.setSpan(new UnderlineSpan() {
        public void updateDrawState(TextPaint tp) {
            tp.setUnderlineText(false);
        }
    }, s.getSpanStart(u), s.getSpanEnd(u), 0);
}
tv.setText(s);

You can use Spannable and URLSpan here to remove hyperlink underline from your code

First of all make your anchor tag text into Spannable

Spannable spannedText = Spannable.Factory.getInstance().newSpannable(
            Html.fromHtml(webLinkText));

Create new class URLSpanNoUnderline and extend it with URLSpan and override updateDrawState method. in that method you can set setUnderlineText to false

then use this method you can remove your link

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

For more information you can visit this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM