如何使 TextView 中的链接可点击

新手上路,请多包涵

我定义了以下 TextView:

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="@string/txtCredits"
    android:autoLink="web" android:id="@+id/infoTxtCredits"
    android:layout_centerInParent="true"
    android:linksClickable="true"/>

其中 @string/txtCredits 是包含 <a href="some site">Link text</a> 的字符串资源。

Android 突出显示 TextView 中的链接,但它们不响应点击。我究竟做错了什么?我必须在我的活动中为 TextView 设置一个 onClickListener 吗?

看起来它与我定义字符串资源的方式有关。

这不起作用:

 <string name="txtCredits"><a href="http://www.google.com">Google</a></string>

但这确实:

 <string name="txtCredits">www.google.com</string>

这是一个无赖,因为我宁愿显示一个文本链接而不是显示完整的 URL。

原文由 Richard 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 914
2 个回答

埋在 API 演示中,我找到了解决问题的方法:

文件 链接.java

     // text2 has links specified by putting <a> tags in the string
    // resource.  By default these links will appear but not
    // respond to user input.  To make them active, you need to
    // call setMovementMethod() on the TextView object.

    TextView t2 = (TextView) findViewById(R.id.text2);
    t2.setMovementMethod(LinkMovementMethod.getInstance());

我删除了 TextView 上的大部分属性以匹配演示中的内容。

 <TextView
    android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/txtCredits"/>

那解决了它。很难发现和修复。

重要提示:不要忘记删除 autoLink="web" 如果您正在调用 setMovementMethod()

原文由 Richard 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 Android 的 Linkify 库 简单地将链接添加到您的 TextView。

添加到您的 strings.xml

 <string name="text_legal_notice">By continuing, you confirm that you have read, understood and agreed to our %1$s and %2$s.</string>
<string name="text_terms_conditions">Terms &amp; Conditions</string>
<string name="text_privacy_policy">Privacy Policy</string>

添加到您的活动中

final String termsConditionsText = getString(R.string.text_terms_conditions);
final String privacyPolicyText = getString(R.string.text_privacy_policy);
final String legalText = getString(
        R.string.text_legal_notice,
        termsConditionsText,
        privacyPolicyText
);
viewBinding.textViewLegalNotice.setText(legalText);

Linkify.addLinks(
        viewBinding.textViewLegalNotice,
        Pattern.compile(termsConditionsText),
        null,
        null,
        (match, url) -> "https://policies.google.com/terms"
);
Linkify.addLinks(
        viewBinding.textViewLegalNotice,
        Pattern.compile(privacyPolicyText),
        null,
        null,
        (match, url) -> "https://policies.google.com/privacy"
);

原文由 Atakan Yildirim 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题