Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm adding an image to my edittext by inserting an ImageSpan. I don't have a thorough understanding of spans but it seems that my ImageSpan needs to wrap a portion of text. So I add some text to the EditText, and wrap it with my ImageSpan and it appears fine. However, when I backspace the ImageSpan, it only deletes one character of the text and the image remains until the entire text is delete. How do I get it to just delete with one 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);
like image 981
dyancat Avatar asked May 15 '14 00:05

dyancat


1 Answers

After some time, I found 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 should create ImageStan with original String like this:

ssb.setSpan(new ImageSpan(bmpDrawable, originalStr), x, x + originalStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
like image 163
Aleksandr Gorshkov Avatar answered Sep 27 '22 16:09

Aleksandr Gorshkov