Reputation: 13
Hi I'm trying to implement emojis to my chat xmpp app.
This is my code to get emoticons in my EditText
private OnClickListener emoclic = new OnClickListener() {
@Override
public void onClick(View v) {
Drawable happySmiley = getActivity().getResources().getDrawable(R.drawable.emo2);
happySmiley .setBounds(0, 0, 22,22);
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("[emo2_anchor]");
builder.setSpan(new ImageSpan(happySmiley), builder.length()-"
[hotel2_anchor]".length(),
builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
chatMsg.getText().append(builder);
}
};
But the result of this is
"hi!!! [emo2_anchor]"
My questions are:
1.- Why [emo2_anchor] is displaying?
2.- How can I display the image?
Upvotes: 1
Views: 144
Reputation: 31497
First, you insert [emo2_anchor]
in your string but use [hotel2_anchor]
for the length.
Second, you have to check if Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
matches your usage of the character indexes or if you have off-by-one errors.
Third, you don't have to use your own placeholders and replacement images. You can just let your users enter the emoji as normal (e.g. from their software keyboard) and have the Unicode code points in the string. The built-in emoji font in Android 4.1.1 will handle the rendering. And if you need support for every API level, this library can help you.
Anyway, try these lines instead:
SpannableStringBuilder builder = new SpannableStringBuilder();
String placeholder = "[emo2_anchor]";
String myText = chatMsg.getText().toString()+" "+placeholder;
builder.append(myText);
builder.setSpan(new ImageSpan(happySmiley), myText.indexOf(placeholder), myText.indexOf(placeholder)+placeholder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
chatMsg.setText(builder);
Upvotes: 1