How to make links in a TextView clickable?

后端 未结 30 3307

I have the following TextView defined:



        
30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 23:45

    The above solutions didn't work for me, but the following did (and it seems a bit cleaner).
    First, in the string resource, define your tag opening chevrons using the HTML entity encoding, i.e.:

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

    and NOT:

    Google
    

    In general, encode all the chevrons in the string like that. BTW, the link must start with http://

    Then (as suggested here) set this option on your TextView:

     android:linksClickable="true"
    

    Finally, in code, do:

    ((TextView) findViewById(R.id.your_text_view)).setMovementMethod(LinkMovementMethod.getInstance());
    ((TextView) findViewById(R.id.your_text_view)).setText(Html.fromHtml(getResources().getString(R.string.string_with_links)));
    

    That's it, no regexes or other manual hacks required.

提交回复
热议问题