问题
I got a edittext and it has multiple coloured text like that code below. Is there any way to store text and colours and show them again? I used to use SharedPreference to store strings integers etc. but this isn`t working for Spannables.
Spannable span1 = new SpannableString("this");
Spannable span2 = new SpannableString("is");
Spannable span3 = new SpannableString("text");
span1.setSpan(new ForegroundColorSpan(Color.parseColor("#292929")), 0, span1.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span2.setSpan(new ForegroundColorSpan(Color.parseColor("#2980b9")), 0, span2.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span3.setSpan(new ForegroundColorSpan(Color.parseColor("#FFFFFF")), 0, span3.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
edittext.setText(TextUtils.concat(span1, span2, span3));
回答1:
You can use Html.toHtml()
to get an HTML representation of the Spannable
, then convert it back using Html.fromHtml()
. However, you will want to test this thoroughly, as not every bit of formatting survives the round-trip.
回答2:
SpannableString is not parceable so you won't be able to save them and recreate them properly. What you can do is save the text and spans separately. The spans are parceable so they will be fine when you recreate them.
Spannable span = new SpannableString("this is text");
span.setSpan(new ForegroundColorSpan(Color.parseColor("#292929")), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span2.setSpan(new ForegroundColorSpan(Color.parseColor("#2980b9")), 5, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span3.setSpan(new ForegroundColorSpan(Color.parseColor("#FFFFFF")), 8, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Save these
String text = span.subString(0, span.length());
List<Span> spans = span.getSpans(0, span.length(), Object.class);
回答3:
According to @CommonsWare answer:
- You need to convert your spanned text to HTML String:
String html = Html.toHtml(yourEditText.getText());
After converting spanned text to string, you can store it in database or Shared Preferences or anything else.
For recover the stored string, you have to restore it and set it to your EditText:
String storedString = //The string you saved it before
yourEditText.setText(Html.fromHtml(storedString));
You have a spanned string now!
来源:https://stackoverflow.com/questions/21444635/android-spannable-text-save-store-issue