如何将图像插入editText

pen*_*ang 3 android android-edittext

我想将图像插入editText,我的代码是:

  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); 
Run Code Online (Sandbox Code Playgroud)

我的代码可以运行,但我有一些不错的经验,我想修改:

1:你知道什么时候使用ss2.setSpan()方法,图像可以替换字符,我只想插入新图像,不要想图像替换字符.

2:你知道我的方法包括"editText.getText()+"";",我添加一些额外的空间,以便图像可以插入最后的CharSequence.如何不需要添加一些额外的,图像也插入最后的CharSequence.

3.当我将图像插入CharSequence的最后一个时,光标不在最后,它出现在CharSequence的前面.如何将光标放在图像后面.

4.i想在不同的CharSequence中不断插入图像,怎么办?

我的问题很多,我希望你能帮助我,非常感谢你.

bab*_*bay 10

做这样的事情(注意:你可以重用SpannableStringBuilder)

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 adds a span to display image where the imageId is. If you do builder.toString() - the string will contain imageId where the imageSpan is.
// you can use it later - if you want to find location of imageSpan in text;
builder.setSpan(imageSpan, selStart, selStart + imgId.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(builder);
Run Code Online (Sandbox Code Playgroud)

注意:有关处理部分删除标记的信息,请参阅后续答案


Par*_*ani 5

试试这个,我希望你正在寻找这个:

   <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/icon">
    </EditText>
Run Code Online (Sandbox Code Playgroud)

您可以尝试同样的事情:

android:drawableRight
android:drawableTop
android:drawableBottom
android:drawablePadding
Run Code Online (Sandbox Code Playgroud)