1 package org.robolectric.shadows; 2 3 import static org.robolectric.util.reflector.Reflector.reflector; 4 5 import android.graphics.Bitmap; 6 import android.graphics.drawable.BitmapDrawable; 7 import android.graphics.drawable.Drawable; 8 import java.io.InputStream; 9 import org.robolectric.annotation.Implementation; 10 import org.robolectric.annotation.Implements; 11 import org.robolectric.annotation.RealObject; 12 import org.robolectric.shadow.api.Shadow; 13 import org.robolectric.util.reflector.Direct; 14 import org.robolectric.util.reflector.ForType; 15 16 @SuppressWarnings({"UnusedDeclaration"}) 17 @Implements(Drawable.class) 18 public class ShadowDrawable { 19 20 @RealObject Drawable realDrawable; 21 22 int createdFromResId = -1; 23 InputStream createdFromInputStream; 24 25 private boolean wasInvalidated; 26 27 /** 28 * Returns an invalid Drawable with the given the resource id. 29 * 30 * @deprecated use {@code ContextCompat.getDrawable(context, resourceId)} 31 */ 32 @Deprecated createFromResourceId(int resourceId)33 public static Drawable createFromResourceId(int resourceId) { 34 Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); 35 BitmapDrawable drawable = new BitmapDrawable(bitmap); 36 ShadowBitmapDrawable shadowBitmapDrawable = Shadow.extract(drawable); 37 shadowBitmapDrawable.validate(); // start off not invalidated 38 shadowBitmapDrawable.setCreatedFromResId(resourceId, null); 39 return drawable; 40 } 41 setCreatedFromResId(int createdFromResId, String resourceName)42 protected void setCreatedFromResId(int createdFromResId, String resourceName) { 43 this.createdFromResId = createdFromResId; 44 } 45 getInputStream()46 public InputStream getInputStream() { 47 return createdFromInputStream; 48 } 49 50 @Implementation invalidateSelf()51 protected void invalidateSelf() { 52 wasInvalidated = true; 53 reflector(DrawableReflector.class, realDrawable).invalidateSelf(); 54 } 55 getCreatedFromResId()56 public int getCreatedFromResId() { 57 return createdFromResId; 58 } 59 wasInvalidated()60 public boolean wasInvalidated() { 61 return wasInvalidated; 62 } 63 validate()64 public void validate() { 65 wasInvalidated = false; 66 } 67 68 @ForType(Drawable.class) 69 interface DrawableReflector { 70 71 @Direct invalidateSelf()72 void invalidateSelf(); 73 } 74 } 75