3

I am combining different strings to show in a TextView. I am doing this using a SpannableStringBuilder, as I need to apply a different color to a few substrings in the string. Now in the combined strings, there are urls which I show in different colors along with some other text. I am doing something like below.

Spannable spannedText = (Spannable) Util.getFormattedText(plainText);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(spannedText);
URLSpan[] urls = strBuilder.getSpans(0, spannedText.length(), URLSpan.class);
for (URLSpan span : urls)
{
    //apply clicks               
}

Output is : Link1 Link2 some links here.

I want to show each url on a different line with the rest of the text after the urls.

eg.

Link1
Link2
some links here

But I am not able to find a solution for this. Any help is appreciated.

Nirav Bhavsar
  • 2,133
  • 2
  • 20
  • 24
user3034944
  • 1,541
  • 2
  • 17
  • 35

2 Answers2

4

You could do like what is mentioned in this answer.

Just use your UrlSpan instead of ImageSpan like below :-

for (URLSpan span : urls)
{
  strBuilder = strBuilder.insert(strBuilder.getSpanEnd(span), System.getProperty("line.separator"));
  //apply clicks     
}
Pooja Gaonkar
  • 1,546
  • 17
  • 27
1

Use SpanableString

    SpannableString spanUrl1 = new SpannableString("www.google.com");
    spanUrl1.setSpan(new ForegroundColorSpan(Color.BLUE), 0, spanUrl1.length(), 
                       Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   Spannable spanUrl2 = new SpannableString("www.stackoverflow.com");
   spanUrl2.setSpan(new ForegroundColorSpan(Color.RED), 0, spanUrl2.length(), 
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

   TV.setText(TextUtils.concat(spanUrl1, "\n",spanUrl2));
   TV.setMovementMethod(LinkMovementMethod.getInstance())
Milan Pansuriya
  • 2,521
  • 1
  • 19
  • 33