How to make links in a TextView clickable?

后端 未结 30 3263

I have the following TextView defined:



        
30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 00:00

    [Tested in Pre-lollipop as well as in Lollipop and above]

    You can get your HTML string from the backend or from your resources files. If you put your text as an resource string, make sure to add the CDATA tag:

    ![CDATA[...Link Title  ...]]
    

    Then in code you need to get the string and assign it as HTML and set a link movement method:

    String yourText = getString(R.string.your_text);
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
       textView.setText(Html.fromHtml(yourText, Html.FROM_HTML_MODE_COMPACT));
    } else {
       textView.setText(Html.fromHtml(yourText));
    }
    
    try {
       subtext.setMovementMethod(LinkMovementMethod.getInstance());
    } catch (Exception e) {
       //This code seems to crash in some Samsung devices.
       //You can handle this edge case base on your needs.
    }
    

提交回复
热议问题