I am trying to do something in an if-statement, this works in every version of android (16 or higher because of the getDrawable) except Android L (tested on latest). The code is the following:
if (item.getIcon().getConstantState().equals(getResources().getDrawable(R.drawable.add_to_fav_normal).getConstantState())
Any help/hints or explanation would be appreciated!
Use item.getContext().getDrawable(int)
or the equivalent ContextCompat
method.
Starting in API 21, all framework widgets that load drawables use Context.getDrawable()
which applies the context's current theme during inflation. This basically just calls getResources().getDrawable(..., getTheme())
internally, so you could also use context.getResources().getDrawable(..., context.getTheme())
.
if (item.getIcon().getConstantState().equals(item.getContext()
.getDrawable(R.drawable.add_to_fav_normal).getConstantState())
In general, though, you shouldn't rely on this check. There are no API guarantees around what constant state you'll receive from a particular drawable.
This solution is convenient for tests only:
public static void assertEqualDrawables(Drawable drawableA, Drawable drawableB) {
Bitmap bitmap1 = ((BitmapDrawable) drawableA).getBitmap();
Bitmap bitmap2 = ((BitmapDrawable) drawableB).getBitmap();
ByteBuffer buffer1 = ByteBuffer.allocate(bitmap1.getHeight() * bitmap1.getRowBytes());
bitmap1.copyPixelsToBuffer(buffer1);
ByteBuffer buffer2 = ByteBuffer.allocate(bitmap2.getHeight() * bitmap2.getRowBytes());
bitmap2.copyPixelsToBuffer(buffer2);
Assert.assertTrue(Arrays.equals(buffer1.array(), buffer2.array()));
}
Based on @alanv's answer, below is what I did and was successful:
if (imgClicked.getDrawable().getConstantState()
.equals(ContextCompat.getDrawable(this,
R.drawable.add_profile).getConstantState())) {
//Both images are same
}else{
//Both images are NOT same
}
Thank's @alanv :)