Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert image to a editText

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

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

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: 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.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.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.

like image 595
pengwang Avatar asked Oct 19 '11 08:10

pengwang


Video Answer


1 Answers

Do something like this (note: you can reuse 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);

Note: See follow up answer for dealing with partial deletion of tags

like image 78
babay Avatar answered Oct 01 '22 06:10

babay