首页 > 解决方案 > 如何在 android Textview 上使用斜线制作可点击的 url 链接

问题描述

我正在使用“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那样编写 URL,那么它可以完美运行,但是当我像https://app.mywebsite.com/terms这样编写 URL 时,链接不是可点击。我可以看到突出显示的链接,但是当单击链接时它不起作用

我该如何解决这个问题?非常感谢。

标签: androidurltextviewclickable

解决方案


创建一个函数,如下所示:

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”&gt;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>"

已移除\"


推荐阅读