Java – Convert between SpannableStringBuilder and CharSequence

Convert between SpannableStringBuilder and CharSequence… here is a solution to the problem.

Convert between SpannableStringBuilder and CharSequence

TextView tv = (TextView) findViewById(R.id.abc);
String rawString = "abcdefg";
SpannableStringBuilder ssb = new SpannableStringBuilder(rawString);
ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, rawString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(ssb);
CharSequence cs = tv.getText();
System.out.println(cs.getClass());

The output is “class android.text.SpannedString”

Why? I want it to be “SpannableStringBuilder” and my conversion (SpannableStringBuilder ssb_2 = (SpannableStringBuilder)cs;) will give an error to the above example.

Also, if I set the buffer type of the TextView to android:bufferType="spannable"

, the output changes to “SpannableString”

Does anyone know why?

Solution

1. The reason it doesn’t work is that it is implemented, meaning CharSequence does not know that SpannableStringBuilder it CharSequencecan be converted to that. (SpannableStringBuilder ssb_2 = (SpannableStringBuilder)cs;) However, you can do it the other way around. Does this make sense?

CharSequence is nothing

SpannableStringBuilder is a: CharSequence, Spannable, Editable, etc.

2. As for whyandroid:bufferType="spannable" it works, you just do what I said above, the other way around. SpannableString CharSequenceSince implemented , it is now its child and can be placed CharSequence in .

But anyway, the correct way to put in CharSequence SpannableStringBuilder is:

SpannableStringBuilder ssb_2 = SpannableStringBuilder(cs);

You might want to brush up on polymorphism:) But you can see this constructor, or at least one of them, in the Android documentation on SpannableStringBuilder’s .


Update:

Based on my observations of the work you do, what is the necessity of use CharSequence ? Just leave the TextView as-is, which means it is returned as a string. So it would be easier to do something like this:

SpannableStringBuilder ssb_2 = SpannableStringBuilder(tv.getText());

This works because String also implements CharSequence, which means it can also be passed as CharSequence a SpannableStringBuilder constructor. Java converts automatically in some cases, including the code above.

Related Problems and Solutions