Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get a SpannableString from a SpannableStringBuilder

Tags:

I am working in a wiki-like parser that creates spans for a set of markup tokens. It is working, but inside the token iterator I frequently need to convert the partial results on a SpannableStringBuilder to a SpannableString. This is called pretty frequently, so I'm after the most efficient solution to do it, and avoid creating extra objects.

At the moment I'm using;

SpannableStringBuilder stuff=complex_routine_that_builds_it(); SpannableString result=SpannableString.valueOf(stuff); 

However this valueOf call internally builds a SpannableString kind of from scratch, doing a toString and a loop to copy assigned spans.

As SpannableStringBuilder name suggests, I think that maybe there's a quicker way to get the SpannableString from the builder. Is it true?

like image 351
rupps Avatar asked Apr 20 '14 08:04

rupps


People also ask

What is SpannableString?

↳ android.text.SpannableString. This is the class for text whose content is immutable but to which markup objects can be attached and detached.

What is spanned in Android?

This is the interface for text that has markup objects attached to ranges of it. Not all text classes have mutable markup or text; see Spannable for mutable markup and Editable for mutable text.


Video Answer


1 Answers

There is no need to convert a SpannableStringBuilder to a SpannableString when you can use it directly, as in a TextView:

SpannableStringBuilder stuff = complex_routine_that_builds_it(); textView.setText(stuff); 

As the question already showed, you could make the conversion if you absolutely had to by

SpannableStringBuilder stuff = complex_routine_that_builds_it(); SpannableString result = SpannableString.valueOf(stuff); 

but you should consider why you would even need to make that conversion? Just use the original SpannableStringBuilder.

SpannableString vs SpannableStringBuilder

The difference between these two is similar to the difference between String and StringBuilder. A String is immutable but you can change the text in a StringBuilder.

Similarly, the text in a SpannableString is immutable while the text in a SpannableStringBuilder is changeable. It is important to note, though, that this only applies to the text. The spans on both of them (even a SpannableString) can be changed.

Related

  • Android Spanned, SpannedString, Spannable, SpannableString and CharSequence
like image 68
Suragch Avatar answered Oct 24 '22 13:10

Suragch