这是我在查看多个Stack Overflow帖子后为自己找到的解决方案。我已经根据您的实现进行了修改:
1. 删除自动链接以使用LinkMovementMethod,并将linksClickable设置为true。
<TextView
android:id="@+id/termsOfUse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textColor="#ffffff"
android:paddingLeft="50dp"
android:paddingRight="50dp"
android:textSize="14sp"
android:clickable="true"
android:linksClickable="true"
android:textColorLink="@color/colorPrimary"
android:text="@string/agree_terms_privacy"/>
如果您使用
android:autoLink="web"
属性,则在调用 TextView 的
setText()
之前,您需要使用
textView.setAutoLinkMask(0);
进行覆盖。如果您愿意,您还可以像Harshal的回答中那样在您的活动中将链接设置为可点击状态,但由于您已经在布局中拥有它,所以我将其保留了下来。 我还给您的 TextView 添加了一个名为
termsOfUse
的ID,稍后我们会用到它。
2. 在 strings.xml 中使用
<
替换 < 并移除 URL 周围的双引号,因为当您检索字符串资源时,它不会正确解析嵌入式 HTML,并且由于某种原因它不会转义双引号。所以,代替:
<string name="agree_terms_privacy">By continuing, you agree to our <a href="http://link1/terms">Terms of Use</a> and read the <a href="http://link1/privacy">Privacy Policy</a></string>
你需要做的是:
<string name="agree_terms_privacy">By continuing, you agree to our <a href=http://link1/terms>Terms of Use</a> and read the <a href=http://link1/privacy>Privacy Policy</a></string>
3. 解析字符串资源并将其绑定到我们的TextView
Spanned policy = Html.fromHtml(getString(R.string.agree_terms_privacy))
TextView termsOfUse = (TextView)findViewById(R.id.termsOfUse)
termsOfUse.setText(policy)
termsOfUse.setMovementMethod(LinkMovementMethod.getInstance())
注意: Html.fromHtml在API 24中已被弃用(有关如何处理此问题,请参见此帖子)。我们使用这种方法从字符串中获取所期望的HTML格式。