SpannableString with Image example

Asahi picture Asahi · Jul 4, 2010 · Viewed 47.6k times · Source

I am looking for an example of how to build and display Android SpannableString with ImageSpan. Something like inline display of smileys.

Thanks a lot.

Answer

Asahi picture Asahi · Jul 5, 2010

Found the following and it seems to do the job:

public class TestActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
            TextView textView  = (TextView) findViewById(R.id.textview); 
            SpannableString ss = new SpannableString("abc"); 
            Drawable d = ContextCompat.getDrawable(this, R.drawable.icon32);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 
            ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE); 
            ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); 
            textView.setText(ss); 
}