Android - Delete entire ImageSpan when part of it is removed?

I add an image to my edittext by inserting ImageSpan. I don’t have a full understanding of spaces, but it seems that my ImageSpan needs to wrap part of the text. So I add text to the EditText and wrap it with ImageSpan, and it looks beautiful. However, when I return ImageSpan, it deletes only one character of the text, and the image remains until all the text is deleted. How can I just delete it with a single backspace?

SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(content.getText());

String imgId = "[some useful text]"; 

int selStart = content.getSelectionStart();

builder.replace(content.getSelectionStart(), content.getSelectionEnd(), imgId);

builder.setSpan(imageSpan, selStart, selStart+imgId.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
content.setText(builder);
+4
source share
1 answer

After a while I found a solution. Try this code:

private TextWatcher watcher = new TextWatcher() {
    private int spanLength = -1;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (start == 0) return;
        if (count > after) {
            ImageSpan[] spans = getEditableText().getSpans(start + count, start + count, ImageSpan.class);
            if (spans == null || spans.length == 0) return;
            for (int i = 0; i < spans.length; i++) {
                int end = getEditableText().getSpanEnd(spans[i]);
                if (end != start + count) continue;
                String text = spans[i].getSource();
                spanLength = text.length() - 1;
                getEditableText().removeSpan(spans[i]);
            }
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (spanLength > -1) {
            int length = spanLength;
            spanLength = -1;
            getEditableText().replace(start - length, start, "");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
};

But you have to create an ImageStan with an original line like this:

ssb.setSpan(new ImageSpan(bmpDrawable, originalStr), x, x + originalStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
+5

Source: https://habr.com/ru/post/1540616/


All Articles