Android delete whole spannable text in EditText

Viewed 1638

I am trying to build a feature like WhatsApp tag person feature in group chat to my Android application. I have created an EditText which will highlight specified characters in the EditText whenever user tap on the person in the table row above as following screen. The original text from EditText will be replaced with HTML code in order to highlight in the EditText

<font color='#0659F4'>@</font><font color='#03A9F4'>displayName</font>

Tag group participant in chat screen

I am trying to implement the delete tag as whole (eg: @Tester Phone) when user delete any single character in the highlighted text of @Tester Phone at EditText.

I have tried to store start index and end index of each tag and listen to EditText cursor position changed event in order for me to decide which tag word to delete but yet I am still unable to achieve my expectation.

Appreciate if any suggestion or method for the implementation.

2 Answers

in list of spans returned, you can get length of each string. Check if there is any length of string that change and remove span at that string

I think you can make your @xxx as a span class. Like

class MentionSpan{
    int start;
    int end;
    String text;
}

Then you can find all your @ targets by spannablestring.getSpans(start,end,MentionSpan.class)

Once you delete a character, check whether the cursor is in side MentionSpans, and if so delete the whole mention span with SpannableStringBuilder.delete(start,end)

Related