【问题标题】:How to add hyperlink for a substring in text of a checkbox in android如何在android中的复选框文本中为子字符串添加超链接
【发布时间】:2015-03-16 15:30:55
【问题描述】:

我的代码:

<CheckBox
         android:id="@+id/checkBox1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:layout_marginBottom="32dp"
         android:text="I agree for terms and conditions"
         android:textColor="#FFFFFF" />

问题

  1. 这里的文字"I agree for terms and conditions",我要 为文本添加超链接"terms and conditions"
  2. 如何实现这一目标

【问题讨论】:

标签: android android-checkbox


【解决方案1】:

你可以这样做

Pattern p = Pattern.compile("click here");
Matcher m = p.matcher("for more info, click here");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
while(result) {
    m.appendReplacement(sb, "some text which contains pattern to linkfy");
    result = m.find();
}
m.appendTail(sb);
String strWithLink = sb.toString();

textView.setText(Html.fromHtml(strWithLink));
textView.setMovementMethod(LinkMovementMethod.getInstance())

【讨论】:

    【解决方案2】:

    我使用Spannable 对象完成了同样的事情,并为每个对象注册了一个不同的ClickableSpan 对象。使用 Spannable,您可以 style 要显示的字符串的方面(文本颜色、前景色/背景色等)

    【讨论】:

    • 好吧,我不同意这种解决方案,因为您最终可能不得不为您的应用程序支持多种语言,这将迫使您编写可怕的大小if-else if-else 代码。
    • 不,你不会。我正在做我的,支持六种不同的语言,并且不使用任何 可怕的大小 if-else-if @Toochka
    【解决方案3】:

    在您的活动/片段中添加以下内容:

    checkBox.setText(
        Html.fromHtml(
            "<a href=\"http://www.google.com\">I agree for terms and conditions</a> "));
    

    【讨论】:

      【解决方案4】:

      在 res->values->string.xml 文件中添加这个

      &lt;string name="string_name"&gt;&lt;a href=/"http://www.example.com"&gt;abc &lt;/a&gt; and &lt;a href=/"http://www.example2.com"&gt;xyz&lt;/a&gt;&lt;/string&gt;

      在代码中

      TextView txt;

      txt.setMovementMethod(LinkMovementMethod.getInstance());

      在 xml 文件中:

      android:text="@string/string_name"

      【讨论】:

        猜你喜欢
        • 2018-09-25
        • 1970-01-01
        • 2014-09-25
        • 2012-11-05
        • 1970-01-01
        • 2019-02-07
        • 1970-01-01
        • 2021-12-03
        • 2015-02-22
        相关资源
        最近更新 更多