Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageSpan not working on Android 5

I have this function that works fine on Android 4.4.1, but breaks on 5.0+.

  public static SpannableStringBuilder prependImage(Drawable drawable, String text) {
    SpannableStringBuilder builder = new SpannableStringBuilder("  " + text);
    builder.setSpan(new ImageSpan(drawable), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return builder;
  }

And I use it like this:

class MyButton extends Button {

    // ... snip ...

    setText(
        prependImage(
            getDrawable(imageResource, color),                     
            getContext().getString(stringResource)),
        BufferType.SPANNABLE);

Here is the getDrawable() method referenced above:

 private Drawable getDrawable(int resource, int color) {
    final Resources resources = getContext().getResources();
    Drawable drawable = resources.getDrawable(resource);
    if (drawable != null) {
      drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
      drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    }
    return drawable;
  }

When I debug, everything seems to succeed, but no image is drawn. Any ideas what I might be doing wrong?

like image 756
i_am_jorf Avatar asked Aug 27 '15 19:08

i_am_jorf


2 Answers

One thing to note, drawable vectors won't work, you must either have a drawable which is a png or jpeg or pass to ImageSpan bitmap instead

like image 71
Ben Levi Avatar answered Nov 10 '22 12:11

Ben Levi


By default, in Material buttons are styled to show text in all-caps. However, there is a bug in the AllCapsTransformationMethod used for capitalization that causes it to discard Spannable data.

You can override the default button styling and disable all-caps by specifying android:textAllCaps="false" on your Button.

<Button
    ...
    android:textAllCaps="false" />

have a look here

like image 34
Shishram Avatar answered Nov 10 '22 12:11

Shishram