I found the solution. All I had to do was to change Spannable.SPAN_INCLUSIVE_INCLUSIVE
to Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
Text is messed up with ImageSpan in EditText
-
07-12-2021 - |
Frage
I am building a simple chat app where the user has the ability to send text and emoticons. I can send both text and emoticons to another phone. My problems are:
1.When I type something and add an emoticon:
Then I cannot type any text right before and right after the image. I can write before the "o" letter. The system "sees" that I type, so even if I type "Honey" after the smiley, I cannot see it, but the EditText registers it and the message is sent:
2.When I add just an emoticon to the Edittext then I delete it, I cannot type anything because the deleted emoticon appears. It appears only once, so no matter how many characters I type, the EditText looks like just before I deleted the emoticon, BUT the text is sent without the emoticon, just like in all three cases.
3.When I type "something" in the EditText then insert an emoticon after "some":
Then I put the cursor after the emoticon and delete it, here what's left:
But the correct message is sent when I press the Send button:
That's what's inside the button listener of the emoticon (this method is activated when I click the emoticon to add it to the EditText).
ib_happy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int cursorPosition = mOutEditText.getSelectionStart();
mOutEditText.getText().insert(cursorPosition, smileys[0]);
SpannableStringBuilder ssb = new SpannableStringBuilder(mOutEditText.getText());
ssb.setSpan(new ImageSpan(bitmapArray.get(0), ImageSpan.ALIGN_BASELINE), cursorPosition, cursorPosition+2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mOutEditText.setText(ssb, BufferType.SPANNABLE);
mOutEditText.setSelection(cursorPosition+2);
dialog_emoticon.dismiss();
}
});
Lösung
Andere Tipps
I would add a textwatcher to that edittext and watch as the user types, that way I can reposition the images/set the text/make corrections/validate input/etc.
editText.addTextChangedListener(textWatcher);
textWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
//editText.doStuffHere
//reposition your image/etc.
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void onTextChanged(CharSequence s, int start, int before, int count) { }
};