Skip to content

Instantly share code, notes, and snippets.

@AlexKorovyansky
Last active January 16, 2017 09:59
Show Gist options
  • Save AlexKorovyansky/bb9e832bcb2ee86e4475 to your computer and use it in GitHub Desktop.
Save AlexKorovyansky/bb9e832bcb2ee86e4475 to your computer and use it in GitHub Desktop.
Espresso ViewMatchers -> withDrawable
public static Matcher<View> withDrawable(final int resourceId) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("with drawable from resource id: " + resourceId);
}
@Override
public boolean matchesSafely(View view) {
try {
final Drawable resourcesDrawable = view.getResources().getDrawable(resourceId);
if (view instanceof ImageView) {
final ImageView imageView = (ImageView) view;
if (imageView.getDrawable() == null) {
return resourcesDrawable == null;
}
return imageView.getDrawable().getConstantState()
.equals(resourcesDrawable.getConstantState());
}
} catch (Resources.NotFoundException ignored) {
}
return false;
}
};
}
@mdelolmo
Copy link

Hi @AlexKorovyansky , have you tested this on a device running Lollipop? I have the feeling it doesn't work, maybe because of the RippleDrawable thing

@TMSantos
Copy link

TMSantos commented Apr 8, 2015

Mdelolmo, it will not work because this:
return imageView.getDrawable().getConstantState()
.equals(resourcesDrawable.getConstantState());

Starting at SDK 21, we have to change the way we compare, the solution would be:
return imageView.getDrawable().getConstantState()
.equals(imageView.getContext().getDrawable(resourceId).getConstantState());

@azizbekian
Copy link

I guess this won't work with vector drawable, will it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment