【问题标题】:set onclick on multiple links in single textview在单个文本视图中设置多个链接的 onclick
【发布时间】:2016-06-11 18:11:55
【问题描述】:

我在数据库中有一个字符串,如下所示:

   string f = "this is the <a href="/page1"> first link</a> and this is the <a href="/page1"> second link</a>"
   textview1.TextFormatted = Html.FromHtml(f);
   url =?
   Intent i = new Intent(Android.Content.Intent.ActionView,url);
   StartActivity(i);

字符串中的链接数不同。我想让 textview 中的所有链接都可点击,当用户点击每个链接时,该链接的 url 将发送到另一个活动。

【问题讨论】:

    标签: android hyperlink xamarin textview clickable


    【解决方案1】:

    当你使用 Html.fromHtml setText 时,'' 被替换为 textView 中的 UrlSpans。 您可以获取每个 url 跨度并为 onClick 函数设置可点击跨度。

    解决方案代码参考this

    【讨论】:

      【解决方案2】:

      我使用 SpannableStringBuilder 也达到了同样的效果。

      只需初始化要添加 2 个或更多侦听器的 TextView,然后将其传递给我创建的以下方法:

      private void customTextView(TextView view) {
                  SpannableStringBuilder spanTxt = new SpannableStringBuilder(
                          getString(R.string.read_and_accept));
                  spanTxt.setSpan(new ForegroundColorSpan(ContextCompat.getColor(activity, R.color.black_30)), 0,
                          getString(R.string.read_and_accept).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                  spanTxt.append(" ");
                  spanTxt.append(getString(R.string.t_and_c));
                  spanTxt.setSpan(new ClickableSpan() {
                      @Override
                      public void onClick(View widget) {
                          Utils.redirectUserToUrl(activity,"http://luxit-driver-terms.tookan.in");
                      }
                  }, spanTxt.length() - getString(R.string.t_and_c).length(), spanTxt.length(), 0);
                  spanTxt.append(" and ");
                  spanTxt.setSpan(new ForegroundColorSpan(ContextCompat.getColor(activity, R.color.accent)), 48, spanTxt.length(), 0);
                  spanTxt.append(getString(R.string.privacy_policy));
                  spanTxt.setSpan(new ClickableSpan() {
                      @Override
                      public void onClick(View widget) {
                          Utils.redirectUserToUrl(activity,"http://luxit-driver-privacypolicy.tookan.in/");
                      }
                  }, spanTxt.length() - getString(R.string.privacy_policy).length(), spanTxt.length(), 0);
                  view.setMovementMethod(LinkMovementMethod.getInstance());
                  view.setText(spanTxt, TextView.BufferType.SPANNABLE);
              }
      

      在 Xml 中,使用 android:textColorLink 为你的链接文本添加自定义颜色

      <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="text"
           android:textColorLink="#000000" />
      

      【讨论】:

        猜你喜欢
        • 2015-07-31
        • 1970-01-01
        • 1970-01-01
        • 2018-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多