0

I have a string in database that is like:

   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);

the number of links in the string is different. I want to make all link in textview clickable and when user click on each of them, the url of that link send to another activity.

Stone
  • 505
  • 2
  • 5
  • 11

2 Answers2

0

When you setText using Html.fromHtml, the '' are replaced as UrlSpans in textView. You can get each of url spans and set clickable spans for onClick function.

Refer to this for the solution code.

Community
  • 1
  • 1
Frosty
  • 500
  • 4
  • 14
0

I have achieved the same using SpannableStringBuilder.

Simply initialize the TextView that you want to add 2 or more listeners and then pass that to the following method that I have created:

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);
        }

In Xml,use android:textColorLink to add custom color for ur link text

<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="text"
     android:textColorLink="#000000" />
Rahul
  • 3,293
  • 2
  • 31
  • 43