17

I am super excited about the new possibility to set vector drawables to layouts using the app:srcCompat="@drawable/icon" attribute introduced in support-library 23.2.0.

But I wonder how I can fetch one of this drawables programmatically or set is as background.

I thought about something like: ContextCompat.getDrawable(context, R.drawable.icon)

Is this even possible?

Langusten Gustel
  • 10,917
  • 9
  • 46
  • 59
  • 2
    I never tried so I'm just guessing, but it seems that there's a static method on VectorDrawableCompat called `createFromResource(Resource, id);` that should work. https://android.googlesource.com/platform/frameworks/support/+/34cbdb2/v7/vectordrawable/src/android/support/v7/graphics/drawable/VectorDrawableCompat.java – Budius Mar 10 '16 at 12:15
  • Doesn't seem to be there with 23.2.0 in Android Studio. – Langusten Gustel Mar 10 '16 at 13:15

1 Answers1

38

Okay, I managed it myself. Thanks for @Budius for pointing me in the right direction.

The Answers lays in VectorDrawable#create()

Resources resources = context.getResources(Resources, int, Theme);
Theme theme = context.getTheme();
Drawable drawable = VectorDrawableCompat.create(resources, R.drawable.drawable, theme);

More input: How to use vector drawables in Android API lower 21?

Community
  • 1
  • 1
Langusten Gustel
  • 10,917
  • 9
  • 46
  • 59
  • 4
    There is not a xml way like `app:srcCompat` for view to use `VectorDrawable` as background. The only way to use `VectorDrawable` as a background pre android lollipop may be **VectorDrawableCompat**, thanks for share. – Seth Sep 02 '16 at 08:55