MentionsEditable extends SpannableStringBuilder implements Parcelable { @Override public void setSpan(Object what, int start, int end, int flags) { if (what instanceof CharacterStyle) { MentionSpan[] mentionSpans = getSpans(start, end, MentionSpan.class); if (mentionSpans != null && mentionSpans.length > 0) { return; } } if ((what == Selection.SELECTION_START || what == Selection.SELECTION_END) && length() == 0) { start = 0; end = 0; } if (start >= 0 && end >= start && end <= length()) { super.setSpan(what, start, end, flags); } else { Log.w(getClass().getName(), "Attempted to set span at invalid indices, start=" + start + ", end=" + end); } } MentionsEditable(@NonNull CharSequence text);  MentionsEditable(@NonNull CharSequence text, int start, int end);  MentionsEditable(@NonNull Parcel in); @Override void setSpan(Object what, int start, int end, int flags); @NonNull @Override SpannableStringBuilder replace(int start, int end, CharSequence tb, int tbstart, int tbend); @NonNull MentionsEditable trim(); @NonNull List<MentionSpan> getMentionSpans(); @Nullable MentionSpan getMentionSpanAtOffset(int index); @Nullable MentionSpan getMentionSpanStartingAt(int index); @Nullable MentionSpan getMentionSpanEndingAt(int index); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Parcelable.Creator<MentionsEditable> CREATOR; }
@Test @TargetApi(14) public void testSetSpan() { final int spanStart = 3; final int spanEnd = 4 + NAME.length(); mEditable.setSpan(mMentionSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); assertEquals(1, mEditable.getSpans(0, mEditable.length(), MentionSpan.class).length); SuggestionSpan suggestionSpan = new SuggestionSpan(ApplicationProvider.getApplicationContext(), new String[0], 0); mEditable.setSpan(suggestionSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); assertEquals(0, mEditable.getSpans(0, mEditable.length(), SuggestionSpan.class).length); mEditable.setSpan(suggestionSpan, 0, spanEnd - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); assertEquals(0, mEditable.getSpans(0, mEditable.length(), SuggestionSpan.class).length); mEditable.setSpan(suggestionSpan, spanStart, spanEnd + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); assertEquals(0, mEditable.getSpans(0, mEditable.length(), SuggestionSpan.class).length); mEditable.setSpan(suggestionSpan, spanEnd, spanEnd + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); assertEquals(1, mEditable.getSpans(0, mEditable.length(), SuggestionSpan.class).length); }