How can I make links in fromHTML clickable? (Android)

后端 未结 5 1271
温柔的废话
温柔的废话 2020-12-04 16:08

This seems like a trivial problem, but is has me kind of stumped. I want to load an HTML string using Html.fromHtml(), and have any links in the string to be clickable and o

相关标签:
5条回答
  • 2020-12-04 16:48
    String data="MyTest";
    
    textView.setText(data);
    textView.setText(Html.fromHtml(data));
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setLinksClickable(true);
    
    0 讨论(0)
  • 2020-12-04 16:53

    As I assumed, the solution was trivial:

    textView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    

    The second line somehow activates the link behavior, although I'm not quite sure how. The same question is addressed over at Google Code.

    0 讨论(0)
  • 2020-12-04 16:54

    As mentioned in other answers, a way forward is to use:

    xtView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    

    However, this won't work if you have ANY android:autoLink value set, not just 'web' as other comments seem to suggest. So that means you can use this solution to linkify URLs at the expense of having phone, email and maps being disabled/unlinked.

    0 讨论(0)
  • 2020-12-04 17:09

    The javadoc of the LinkMovementMethod says that it

    Supports clicking on links with DPad Center or Enter.

    So it makes sense that works that way.

    And confirmed, with 4.2.2 works like charm with just the

    textView.setMovementMethod(LinkMovementMethod.getInstance());
    
    0 讨论(0)
  • 2020-12-04 17:09

    It should be this way:

    textView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
    textView.setAutoLinkMask(Linkify.WEB_URLS);
    textView.setLinksClickable(true);
    

    in XML should be

    <TextView
        android:id="@+id/txtview"
        android:autoLink="web"
        android:linksClickable="true"
        />
    
    0 讨论(0)
提交回复
热议问题