I am making a simple chat application and I want to show emoticons on edittext when writing a message.
I have this to identify that characters will be replaced by Image throught ImageSpan (this is only called when an emoticon character is inserted in the EditText):
for (index = start; index < start+num_chars; index++) { if (index + 1 > editable.length()) continue; if(emoticons.containsKey(editable.subSequence(index, index + 1).toString())){ int length=1; Drawable drawable = context.getResources().getDrawable(emoticons.get(editable.subSequence(index, index + 1).toString())); Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); int size=Utils.GetDipsFromPixel(context, (int)(textSize*1.3)); Drawable d = new BitmapDrawable(Bitmap.createScaledBitmap(bitmap, size, size, true)); int dWidth = d.getIntrinsicWidth(); int dHeight = d.getIntrinsicHeight(); d.setBounds(0 , -dHeight, dWidth, 0); ImageSpan span; span = new ImageSpan(d,ImageSpan.ALIGN_BASELINE); editable.setSpan(span, index, index + length,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); index += length - 1; } }
I use the SPAN_EXCLUSIVE_EXCLUSIVE tag to set the range, but I have problems with the swiftkey keyboard, because when I insert a smiley into the edittext, everything that I write immediately after imageSpan is held below the image (for example, SPAN_EXCLUSIVE_INCLUSIVE). With the default Android keyboard, I don't have this problem.
I just want the whatsapp application to perform the same behavior using emoticons in EditText.
Any suggestions? Any change I have to make with my code?
EDIT: the variable "editable" is passed to the method. This is the value of txtMessage.getText (), where txtMessage is an EditText.
Thanks!
EDIT: Use only one piece of code! This works well in multi-line mode! I think the problem was using Drawable-> Bitmap-> ResizedBitmap-> Drawable.
public static final HashMap<String, Integer> emoticons = new HashMap(); static { emoticons.put("\ue415", R.drawable.e415); emoticons.put("\ue056", R.drawable.e056); emoticons.put("\ue057", R.drawable.e057); ... public static Spannable getSmiledText(Context context, Spannable editable, int start, int num_chars, float textSize) { int index; for (index = start; index < start + num_chars; index++) { if (index + 1 > editable.length()) continue; if (EmojiLayout.emoticons.containsKey(editable.subSequence(index, index + 1).toString())) { int length = 1; Bitmap smiley = BitmapFactory.decodeResource(context.getResources(), ((Integer) EmojiLayout.emoticons.get(editable.subSequence(index, index + 1).toString()))); int size = Utils.GetDipsFromPixel(context, (int) (textSize * 1.37)); Bitmap scaledbmp=Bitmap.createScaledBitmap( smiley, size, size, false); ImageSpan span; span = new ImageSpan(scaledbmp); Log.d("EmojiLayout", "Index: " + String.valueOf(index) + "To: " + String.valueOf(index + length)); editable.setSpan(span, index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); index += length - 1; } } return editable; }