I want to insert a image to a editText my code is:
CharSequence charSeq= editText.getText()+\" \";
SpannableString ss2 = new SpannableString(charSeq);
I guess, You'll also need some functionality for text-editing: image should be removed if one character of it is removed; this class can help (removes all the image text-placeholder if a char of it is removed)
public class ImageSpanTextWatcher implements TextWatcher {
Object[] mTouchedSpans;
int[] mSpanLength;
boolean replacing = false;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (s instanceof SpannableStringBuilder) {
SpannableStringBuilder ssb = (SpannableStringBuilder) s;
mTouchedSpans = ssb.getSpans(start, start + count, ImageSpan.class);
if (mTouchedSpans != null && mTouchedSpans.length > 0) {
mSpanLength = new int[mTouchedSpans.length];
for (int i = 0; i < mTouchedSpans.length; i++) {
mSpanLength[i] = ssb.getSpanEnd(mTouchedSpans[i]) - ssb.getSpanStart(mTouchedSpans[i]);
}
}
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s instanceof SpannableStringBuilder) {
SpannableStringBuilder ssb = (SpannableStringBuilder) s;
if (replacing)
return;
replacing = true;
if (mTouchedSpans != null && mTouchedSpans.length > 0)
for (int i = 0; i < mTouchedSpans.length; i++) {
int newLen = ssb.getSpanEnd(mTouchedSpans[i]) - ssb.getSpanStart(mTouchedSpans[i]);
if (newLen < mSpanLength[i]) {
ssb.replace(ssb.getSpanStart(mTouchedSpans[i]), ssb.getSpanEnd(mTouchedSpans[i]), "");
}
}
mTouchedSpans = null;
mSpanLength = null;
replacing = false;
}
}
@Override
public void afterTextChanged(Editable s) {}
}