1

Two input string, for example:

1. Hyper link input:

"<a href=\"https://blog.twitter.com/official/en_us/topics/company/2018/keeping-your-account-secure.html\">Что случилось с паролями в логах Twitter</a>"

2. Simple URL:

https://www.youtube.com/watch?v=2Cj6CbC-DkU

TextView class has two ways how we could highlight links and make them clickable:

1. through the code:

TextView.setMovementMethod(LinkMovementMethod.getInstance());

2. through the XML:

android:autoLink="web"

The known issue that to handle hyper links we should use the first method with LinkMovementMethod, and remove the xml attribute "autoLink".

The point is that when I use this solution, my textView ignores the simple links(second input string from example). And vice versa - if I use the XML solution, textView will ignore hyper links.

The question is what should I use to support both: hyper links and simple urls?

Maxim Petlyuk
  • 1,014
  • 14
  • 20

1 Answers1

0

Let say you want to hyperlink word Twitter you could accomplish that using SpannableStringBuilder for example:

 SpannableStringBuilder spanTxt = new SpannableStringBuilder(
            "Что случилось с паролями в логах ");
    spanTxt.append("Twitter");
    spanTxt.setSpan(new ClickableSpan() {
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(ContextCompat.getColor(context, R.color.pick_button_color)); //Your color for hyperlinked word
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget) {
           // Handle click on Twitter
        }
    }, spanTxt.length() - "Twitter".length(), spanTxt.length(), 0);
    spanTxt.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.pick_button_color)), 33, spanTxt.length(), 0);  // I put 33 check did I count correctly

    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(spanTxt, TextView.BufferType.SPANNABLE);
Yupi
  • 4,402
  • 3
  • 18
  • 37
  • The purpose of this task is to show not predefined text(e.g.: some API response). I believe that it`s complicated solution to find links manually and build spans by hands, considering that this job has been already done by LinkMovementMethod class. Seems that I'm missing something, since I do not see a universal solution – Maxim Petlyuk May 20 '18 at 23:35