How to merge some spannable objects?

I divide a spannable object into 3 parts, do different operations, and then I need to merge them.

Spannable str = editText.getText();
Spannable selectionSpannable = new SpannableStringBuilder(str, selectionStart, selectionEnd);
Spannable endOfModifiedSpannable = new SpannableStringBuilder(str, selectionEnd, editText.getText().length());
Spannable beginningOfModifiedSpannable = new SpannableStringBuilder(str, 0, selectionStart);            

How can I do it? I haven't found the required method or constructor to do it.


Solution 1:

You could use this:

TextUtils.concat(span1, span2);

http://developer.android.com/reference/android/text/TextUtils.html#concat(java.lang.CharSequence...)

Solution 2:

Thanks, it works. I have noticed that I can merge even 3 spannable object:

(Spanned) TextUtils.concat(foo, bar, baz)

Solution 3:

I know this is old. But after modifying kotlin stdlib a bit I've got this code:

fun <T> Iterable<T>.joinToSpannedString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): SpannedString {
    return joinTo(SpannableStringBuilder(), separator, prefix, postfix, limit, truncated, transform)
            .let { SpannedString(it) }
}

Hope it might help somebody.

Solution 4:

Use SpannableStringBuilder.

Even better- make a kotlin operator overload:

operator fun Spannable.plus(other: Spannable): Spannable{
    return SpannableStringBuilder(this).append(other)
}

just throw that in any kotlin file as a top level function.

and the you can concatenate using +:

val spanA = ...
val spanB = ...

val concatenatedSpan = spanA + spanB