如何插入图片到EDITTEXT插入图片、EDITTEXT

2023-09-06 13:11:59 作者:一笑泯恩怨

我要插入一个图像到EDITTEXT我的code是:

I want to insert a image to a editText my code is:

  CharSequence charSeq= editText.getText()+" ";
  SpannableString ss2 = new SpannableString(charSeq); 
  Drawable d2 = holder.image.getDrawable(); 
  d2.setBounds(0, 0, d2.getIntrinsicWidth(), d2.getIntrinsicHeight()); 

  ImageSpan span2 = new ImageSpan(d2, ImageSpan.ALIGN_BASELINE); 
  ss2.setSpan(span2,charSeq.length()-1, charSeq.length(),  

  Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

  editText.setText(ss2,BufferType.SPANNABLE); 

我的code能运行,但我有一些不愉快的经历,我想修改:

My code can run but i have some not bad experience i want to modify:

1:你知道,当使用ss2.setSpan()方法中,图像可替代的特点,我只需要插入新的形象,DONOT想要的图像替换字符

1: You know when use ss2.setSpan() method, the image can replace the character, i only want to insert new image, donot want to the image replace the character.

2:你知道我的方法包括editText.getText()+;,我添加一些额外的空间,从而使图像可以插入到最后的CharSequence的。如何能不加添加一些额外的形象也插入到最后的CharSequence的。

2: you know my method include "editText.getText()+" ";", i add some Extra space, so that the image can insert to the last of the CharSequence. how to not need add add some Extra, the image also insert to the last of the CharSequence.

3,当我插入图像到最后的CharSequence,光标无法在最后的,它出现在的CharSequence的前面。如何把光标放在背后的形象。

3.when i insert the image to the last of the CharSequence, the cursor not at the last, it appear in the front of the CharSequence. how to put the cursor at the behind the image.

4。我希望不断插入的CharSequence的,怎么办?

4.i want to constantly insert the image in the different of the CharSequence,how to do?

我的问题这么多,我希望你能帮助我感谢你非常非常多。

My question so many, I want you can help me thank you very very much.

推荐答案

这样的事情(这是冷杉版本 - 你不需要重新创建商 - 您可以重复使用旧的)

something like this (that was firs version- you don't need to re-create builder - you can reuse old one)

editText = (EditText)mRoot.findViewById(R.id.content);
ImageSpan imageSpan = new ImageSpan(preview);

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

// this is a string that will let you find a place, where the ImageSpan is.
String imgId = "[img=1]"; 

int selStart = editText.getSelectionStart();

// current selection is replaceв with imageId
builder.replace(editText.getSelectionStart(), editText.getSelectionEnd(), imgId);

// this "replaces" imageId string with image span. If you do builder.toString() - the string will contain imageIs where the imageSpan is.
// you can yse this later - if you want to location of imageSpan in text;
builder.setSpan(imageSpan, selStart, selStart + imgId.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(builder);