我正在通过插入ImageSpan将图像添加到我的edittext中。我对跨度没有足够的了解,但是我的ImageSpan似乎需要换行一部分文本。所以我在EditText中添加了一些文本,并用ImageSpan包裹起来,看起来很好。但是,当我退格ImageSpan时,它仅删除文本的一个字符,并且图像一直保留到删除整个文本为止。我如何只用一个退格键删除它?

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);

最佳答案

一段时间后,我找到了解决方案。试试下面的代码:

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) {
    }
};

但是您应该使用原始String创建ImageStan,如下所示:
ssb.setSpan(new ImageSpan(bmpDrawable, originalStr), x, x + originalStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

10-08 17:37