在单个textview中设置onclick多个链接

时间:2016-02-28 19:20:59

标签: android hyperlink xamarin textview clickable

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

   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中的所有链接都可以点击,当用户点击每个链接时,该链接的网址会发送到另一个活动。

2 个答案:

答案 0 :(得分:0)

使用Html.fromHtml设置文本时,&#39;&#39;在textView中替换为UrlSpans。 您可以获取每个网址跨度并为onClick功能设置可点击的范围。

有关解决方案代码,请参阅this

答案 1 :(得分:0)

我使用 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" />
相关问题