Add extra line in SpannableStringBuilder getSpans()

1.2k views Asked by At

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.

2

There are 2 answers

0
Pooja Gaonkar On BEST ANSWER

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     
}
3
Milan Pansuriya On

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