How to display image in Android's TextView?

I want to inset some images in the TextView. How to do it? Any idea


Solution 1:

You can create a spannableString and place your image where you want in the TextView. Or you can use

ImageSpan is = new ImageSpan(context, resId);
text.setSpan(is, index, index + strLength, 0);

Solution 2:

Much easier you can use SpannableStringBuilder from API 1

Example usage:

For API >= 21

    SpannableStringBuilder builder = new SpannableStringBuilder();
    builder.append("My string. I ")
            .append(" ", new ImageSpan(getActivity(), R.drawable.ic_action_heart), 0)
            .append(" Cree by Dexode");

    textView.setText(builder);

For API >= 1

    SpannableStringBuilder builder = new SpannableStringBuilder();
    builder.append("My string. I ").append(" ");
    builder.setSpan(new ImageSpan(getActivity(), R.drawable.ic_action_heart),
            builder.length() - 1, builder.length(), 0);
    builder.append(" Cree by Dexode");

    textView.setText(builder);

Solution 3:

ImageSpan is = new ImageSpan(context, R.drawable.arrow);
SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");
text.setSpan(is, 5, 5 + 10, 0);

Solution 4:

do something like this.

textView.setCompoundDrawableWithIntrinsicBounds(yourImg, null, null, null);