I'm trying to put emoticons inside a EditText. I've managed to do it and it works fine but I have a problem when I try to delete these emoticons from the EditText using the soft keyboard. I can't do this action with a single delete button's click. When I insert a new ImageSpan I replace an imageId for it but when I try to delete de icon I have to delete all the imageId characters before delete the image.
String fileName = "emoticon1.png";
Drawable d = new BitmapDrawable(getResources(), fileName);
String imageId = "[" + fileName + "]";
int cursorPosition = content.getSelectionStart();
int end = cursorPosition + imageId.length();
content.getText().insert(cursorPosition, imageId);
SpannableStringBuilder ss = new SpannableStringBuilder(content.getText());
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, cursorPosition, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
content.setText(ss, TextView.BufferType.SPANNABLE);
content.setSelection(end);
I need to remove the emoticons with a single delete button's click. Could you help me, please?
Thanks!
This is the implementation to handle emoticons inside a
EditText
. This implementation uses theTextWatcher
to monitor theEditText
changes and detect if some emoticon was removed when some text is deleted.Note that this implementation also verifies if a text selection was deleted (not only the delete key).
To avoid issues with text prediction when typing a text, it is recommended to surround the emoticon text with spaces (the text prediction can join the emoticon text with the adjacent text).