Arrayoutofboundsexception using setspan
I receive an arrayoutofboundsexception error. When I attempt to format a draft text message to be displayed. This is just a simple text-messaging app and I am attempting to set the text size and color. When I comment these two lines my app does not crash but is not formatt开发者_JS百科ed as I would like.
The error occurs at:
buf.setSpan(new TextAppearanceSpan(getContext(), size, color), before,
buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
Here is the entire code:
private CharSequence formatMessage(ConversationListItemData ch) {
final int size = android.R.style.TextAppearance_Small;
final int color = android.R.attr.textColorSecondary;
String from = ch.getFrom();
SpannableStringBuilder buf = new SpannableStringBuilder(from);
if (ch.getMessageCount() > 1) {
buf.append(" (" + ch.getMessageCount() + ") ");
}
int before = buf.length();
if (ch.hasDraft()) {
buf.append(" ");
buf.append(getContext().getResources().getString(R.string.has_draft));
buf.setSpan(new TextAppearanceSpan(getContext(), size, color), before,
buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
buf.setSpan(new ForegroundColorSpan(
getContext().getResources().getColor(R.drawable.text_color_red)),
before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
// Unread messages are shown in bold
if (!ch.isRead()) {
buf.setSpan(STYLE_BOLD, 0, buf.length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
return buf;
}
I figured it out. You cannot use the TextAppearanceSpan constructor that has 3 parameters when using ForegroundColorSpan. I changed the line below by removing the color variable parameter:
buf.setSpan(new TextAppearanceSpan(getContext(), size, color), before,
buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
to
buf.setSpan(new TextAppearanceSpan(getContext(), size), before,
buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
精彩评论