问题描述
我正在通过插入ImageSpan将图像添加到我的edittext中.我对跨度没有足够的了解,但是我的ImageSpan似乎需要换行一部分文本.所以我在EditText中添加了一些文本,并用ImageSpan包裹起来,看起来很好.但是,当我退格ImageSpan时,它仅删除文本的一个字符,并且图像一直保留到删除整个文本为止.如何只用一个退格键删除它?
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);
推荐答案
一段时间后,我找到了解决方案.尝试以下代码:
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) {
}
};
但是您应该使用以下原始String创建ImageStan:
But you should create ImageStan with original String like this:
ssb.setSpan(new ImageSpan(bmpDrawable, originalStr), x, x + originalStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
这篇关于Android-删除部分ImageSpan时删除整个ImageSpan?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!