Android开发:如何让TextView中含超链接的String对象正确显示可点击链接
Android TextView HTML超链接可点击实现方案
问题根源
当前实现存在两个核心问题:
- 字符串内的
<a>标签被转义成了HTML实体(<对应<、>对应>),无法直接被识别为HTML标签 Linkify.addLinks()仅能识别纯文本中直接暴露的URL地址,无法解析封装在<a>标签内的超链接
修复代码示例
import android.text.Html; import android.text.method.LinkMovementMethod; import android.widget.TextView; // 原有字符串定义 String description = "\"Cardano is a decentralised platform" + " that will allow complex programmable transfers of" + " value in a secure and scalable fashion. It is one" + " of the first blockchains to be built in the highly" + " secure Haskell programming language. Cardano is developing" + " a <a href=\\\"https://www.coingecko.com/en?category_id=29\\\">smart contract platform</a>" + " which seeks to deliver more advanced features than any protocol previously developed." + " It is the first blockchain platform to evolve out of a scientific philosophy and a research-first driven approach." + " The development team consists of a large global collective of expert engineers and researchers.\\r\\n\\r\\n" + "The Cardano project is different from other blockchain projects as it openly addresses the need for regulatory oversight whilst maintaining" + " consumer privacy and protections through an innovative software architecture."; TextView textView = findViewById(R.id.description_textview); // 第一步:还原转义的HTML实体,得到正常的HTML字符串 String unescapedHtml = Html.fromHtml(description, Html.FROM_HTML_MODE_LEGACY).toString(); // 第二步:解析HTML内容为带Span的富文本对象 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { textView.setText(Html.fromHtml(unescapedHtml, Html.FROM_HTML_MODE_LEGACY)); } else { // 低版本Android兼容 textView.setText(Html.fromHtml(unescapedHtml)); } // 第三步:设置链接点击支持,必须添加否则超链接无法响应点击 textView.setMovementMethod(LinkMovementMethod.getInstance());
可选优化
如果需要自定义超链接颜色、去掉下划线、自定义点击逻辑,可以通过重写ClickableSpan实现:
- 遍历解析后的
Spanned对象里的所有URLSpan - 替换为自定义的
ClickableSpan,修改样式和点击逻辑
内容的提问来源于stack exchange,提问作者AtomicallyBeyond
相关产品推荐
相关产品推荐

