如何在Android Textview上使可点击的URL链接带有斜线

时间:2019-11-06 08:40:51

标签: android url textview clickable

我正在使用“ setMovementMethod”使TextView上的URL可点击。最好看下面的代码:

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());

问题在于网址“ .com”之后的斜杠。如果我删除该斜杠,并且写出类似https://app.mywebsite.com的网址,则它可以正常工作,但是当我写出类似https://app.mywebsite.com/terms的网址时,则该链接不可单击。我可以看到该链接突出显示,但是当单击该链接时它不起作用

我该如何解决?非常感谢。

2 个答案:

答案 0 :(得分:0)

首先,

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

是非法的,因为-不允许在另一个双引号内使用双引号,即“。”

因此,正确的格式应为:

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

进行此更改时,我可以单击链接,否则,代码甚至无法编译。

其次,检查Build版本并使用Html.fromHtml(string, int)

的两个参数版本

有关更多信息,请访问here

答案 1 :(得分:0)

创建一个如下所示的函数

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

如下所示将您的字符串添加到string.xml文件中:

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

并通过添加代码来使用它:

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

或者您可以将value变量编辑为:

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>"

已删除\"