简体   繁体   中英

How to make clickable an url link with slash on an android Textview

I am using the "setMovementMethod" to make clickable an url on a TextView. Better look the follow code:

1. String value = "By signing up, you agree to our <a href=\"https://app.mywebsite.com/terms\">My App Term</a> and confirm that you have read our <a href=\"https://app.mywebsite.com/privacypolicy\">Privacy Policy</a>";

2. TextView text = (TextView) findViewById(R.id.text);

3. text.setText(Html.fromHtml(value));

4. text.setMovementMethod(LinkMovementMethod.getInstance());

The problem is about the slash just after ".com" of the url. If I remove that slash and I write the url like that https://app.mywebsite.com then it works perfectly but when I write the url like that https://app.mywebsite.com/terms then the link isn't clickable. I can see the link highlighted but when click on the link then it does not work

How I could resolve this? Thank you very much.

Firstly,

String value = "By signing up, you agree to our <a href="https://app.mywebsite.com/terms">My App Term</a> and confirm that you have read our <a href="https://app.mywebsite.com/privacypolicy">Privacy Policy</a>";

is illegal because - you are not allowed to use double-quote ie " inside another double-quote.

So, the correct form should be:

String value = "By signing up, you agree to our <a href='https://app.mywebsite.com/terms'>My App Term</a> and confirm that you have read our <a href='https://app.mywebsite.com/privacypolicy'>Privacy Policy</a>";

When I do this change, I am able to click the link, or else, the code will not even compile.

Secondly, have a check on the Build version and use the two parameter version of the Html.fromHtml(string, int)

More information on it is here :

Create a function look like:

fun applyHtmlToTextView(tv: TextView?, html: String) {
    if (tv == null)
        return

    tv.movementMethod = LinkMovementMethod.getInstance()

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        tv.text = Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
    } else {
        tv.text = Html.fromHtml(html)
    }
}

Add your string to the string.xml file as below:

<string name="lb_your_string"><![CDATA[<a href="https://google.com”>Google.</a>]]></string>

And using it by adding the code:

applyHtmlToTextView(tv, getString(R.string.lb_your_string))

OR you can edit the value variable to:

String value = "By signing up, you agree to our <a href=https://app.mywebsite.com/terms>My App Term</a> and confirm that you have read our <a href=https://app.mywebsite.com/privacypolicy>Privacy Policy</a>"

Removed \"

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