我在下面使用textwatcher在多行模式下使用editText,但editText行为很奇怪。 Evertime我的编辑文本中有超过1个图像跨度,并尝试在它们之间写入文本,文本将以其中一个跨度编写。
public class Messenger_Image_Handler implements TextWatcher{
private final EditText editText;
private final ArrayList<ImageSpan> imagesToRemove = new ArrayList<ImageSpan>();
private final ArrayList<Char_SpanEnd_Holder> charToChange = new ArrayList<Char_SpanEnd_Holder>();
public Messenger_Image_Handler(EditText editText)
{
this.editText = editText;
}
public void insertImage(String imgPattern, Drawable d)
{
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
// Get the selected text.
int start = editText.getSelectionStart();
int end = editText.getSelectionEnd();
Editable message = editText.getEditableText();
// Insert the image
message.replace(start, end, imgPattern);
message.setSpan(span, start, start + imgPattern.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
// Check if some text will be removed.
if (count > 0)
{
int end = start + count;
Editable message = editText.getEditableText();
ImageSpan[] list = message.getSpans(start, end, ImageSpan.class);
for (ImageSpan span : list)
{
// Get only the images that are inside of the changed
// region.
int spanStart = message.getSpanStart(span);
int spanEnd = message.getSpanEnd(span);
if ((spanStart < end) && (spanEnd > start))
{
// Add to remove list
imagesToRemove.add(span);
}
}
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s)
{
//Commit the images to be removed.
for (ImageSpan span : imagesToRemove)
{
Editable message = editText.getEditableText();
int start = message.getSpanStart(span);
int end = message.getSpanEnd(span);
// Remove the span
message.removeSpan(span);
// Remove the remaining image text.
if (start != end)
{
message.delete(start, end);
}
}
imagesToRemove.clear();
}
}
这是我用来创建我的跨度的函数:
private void insertNewImageIntoEditText(String path)
{
//Create bitmap
File image = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
Drawable d = new BitmapDrawable(bitmap);
//Increase current pictures
pictureID ++;
//Current Img Pattern with id
String imgPattern = "[#!-" + pictureID + "-!#]";
//Add img to the hashmap
//picturesHashMap.put(imgPattern, path);
imageHandler.insertImage(imgPattern, d);
}
图片ID和图片散列图用于稍后识别图片位置。 如果编辑文本中只有一张图片,则文本如下所示:“测试测试[#! - 1 - !#]测试测试”。但是,如果我使用2或更多并尝试在它们之间写,文本看起来像这样:“测试[#! - 1 - !#testtest] [#! - 2 - !#]”。 我希望有人找到解决这个问题的方法。