7

How to set Drawable from xml vector inside an ImageSpan? I use this two methods below. But my icon didn't show. When I use png from drawable resource icon shows up. Any idea?

private void setupEmptyListInfoBox() {
        Drawable icon = loadVectorFromResources(getActivity(), R.drawable.ic_add_circle_24dp);
        ImageSpan is = new ImageSpan(icon, DynamicDrawableSpan.ALIGN_BASELINE);
        String info = getString(R.string.empty_weight_list_info);
        int iconPosition = info.indexOf("|");

        SpannableString text = new SpannableString(info);
        text.setSpan(is, iconPosition, iconPosition + 1, 0);

        mEmptyListInfo.setText(text);
    }

public static Drawable loadVectorFromResources(Context context, int resId) {
    Drawable drawable;
    if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = VectorDrawableCompat.create(context.getResources(), resId, context.getTheme());
    } else {
        drawable = context.getResources().getDrawable(resId, context.getTheme());
    }
    return drawable;
}
crgarridos
  • 8,758
  • 3
  • 49
  • 61
kazhiu
  • 749
  • 9
  • 21

1 Answers1

4

I have just managed to load a vector into an ImageSpan by doing:

Drawable myDrawable = AppCompatResources.getDrawable(context, R.drawable.my_drawable);
myDrawable.setBounds(0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());

ImageSpan myImageSpan = new ImageSpan(myDrawable, ImageSpan.ALIGN_BASELINE);
SpannableString mySpannableString = new SpannableString(context.getString(R.string.my_string));
mySpannableString.setSpan(myImageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

I hope that helps.

argenkiwi
  • 2,134
  • 1
  • 23
  • 26
  • Icon has parent layout maximum width and height with this code, setBounds doesnt do anything even if i do something like setBound(0,0,,20,20), do you have any solution for that? how we can scale vector xml drawables? – CDrosos Aug 30 '20 at 12:58