4

I need to add more than one smileys in a single edittext box. For add a single smiley I follow this link

How to add more smileys in a single Edittext box? Thanks in advance..

Finder
  • 1,217
  • 5
  • 18
  • 46

2 Answers2

14

You can add as many ImageSpans to a Spannable as you like. Just follow the concept laid out by the code you're linking. You probably want to use a SpannableStringBuilder too.

Drawable happySmiley = mContext.getResources().getDrawable(R.drawable.happy);
happySmiley .setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
Drawable sadSmiley = mContext.getResources().getDrawable(R.drawable.sad);
sadSmiley .setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Some text [happy_smiley_anchor]");
builder.setSpan(new ImageSpan(happySmiley), builder.length()-"[happy_smiley_anchor]".length(), builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(". Some more text [sad_smiley_anchor]");
builder.setSpan(new ImageSpan(sadSmiley), builder.length()-"[sad_smiley_anchor]".length(), builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

edittext.setText(builder);

Obviously you can use any anchor text/character you like - it gets replaced when the ImageSpan is inserted. It might even work with an empty char/string, but I didn't try that.

NorthCat
  • 9,643
  • 16
  • 47
  • 50
MH.
  • 45,303
  • 10
  • 103
  • 116
  • In this example it replaces the text from start till the end with the imagespan object...Do u have any idea how to put an imagespan just where the cursor is? – Shail Adi Jun 26 '13 at 12:13
  • 1
    @ShailAdi: Did you try to simply set the `ImageSpan` with equal start and end (at the position of the text caret)? Alternatively, you may be need to insert a placeholder character first. And if all else fails, just start a new question here on SO. :) – MH. Jun 26 '13 at 19:10
  • @MH. yeah...I tried with the equal start and end, and it does not place the image at all... started using placeholder char for it. Thanks :) – Shail Adi Jun 27 '13 at 07:58
1

You can add as many ImageSpans to a Spannable as you like. Just follow the concept laid out by the code you're linking. You probably want to use a SpannableStringBuilder too.

SpannableStringBuilder ssb = new SpannableStringBuilder("Some Text"); 
Bitmap image1 = BitmapFactory.decodeResource( getResources(), R.drawable.yourimage1 ); 
Bitmap image2 = BitmapFactory.decodeResource( getResources(), R.drawable.yourimage1 ); ssb.setSpan( new ImageSpan( image1 ), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE );
ssb.setSpan( new ImageSpan( image2 ), 2,3, Spannable.SPAN_INCLUSIVE_INCLUSIVE ); 
deleteButton.setText( ssb, BufferType.SPANNABLE );

I tried above code and it works fine. I added two image span in one text view, likewise you can add as many image span to textview.

NorthCat
  • 9,643
  • 16
  • 47
  • 50