Comparing two drawables in android

Update https://stackoverflow.com/a/36373569/1835650

getConstantState() works not well

There is another way to compare:

mRememberPwd.getDrawable().getConstantState().equals
            (getResources().getDrawable(R.drawable.login_checked).getConstantState());

mRemeberPwd is an ImageView in this example. If you're using a TextView, use getBackground().getConstantState instead.


Relying on getConstantState() alone can result in false negatives.

The approach I've taken is to try comparing the ConstantState in the first instance, but fall back on a Bitmap comparison if that check fails.

This should work in all cases (including images which aren't resources) but note that it is memory hungry.

public static boolean areDrawablesIdentical(Drawable drawableA, Drawable drawableB) {
    Drawable.ConstantState stateA = drawableA.getConstantState();
    Drawable.ConstantState stateB = drawableB.getConstantState();
    // If the constant state is identical, they are using the same drawable resource.
    // However, the opposite is not necessarily true.
    return (stateA != null && stateB != null && stateA.equals(stateB))
            || getBitmap(drawableA).sameAs(getBitmap(drawableB));
}

public static Bitmap getBitmap(Drawable drawable) {
    Bitmap result;
    if (drawable instanceof BitmapDrawable) {
        result = ((BitmapDrawable) drawable).getBitmap();
    } else {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        // Some drawables have no intrinsic width - e.g. solid colours.
        if (width <= 0) {
            width = 1;
        }
        if (height <= 0) {
            height = 1;
        }

        result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
    }
    return result;
}

My question was for just comparing two drawables, I tried but could not get any method that directly compare two drawables,however for my solution i changed drawable to bitmap and then comparing two bitmaps and that is working.

Bitmap bitmap = ((BitmapDrawable)fDraw).getBitmap();
Bitmap bitmap2 = ((BitmapDrawable)sDraw).getBitmap();

if(bitmap == bitmap2)
    {
        //Code blcok
    }

for SDK 21+

this works in SDK -21

mRememberPwd.getDrawable().getConstantState().equals
        (getResources().getDrawable(R.drawable.login_checked).getConstantState())

for SDK +21 android 5. set drawable id to imageview with tag

img.setTag(R.drawable.xxx);

and compare like this

if ((Integer) img.getTag() == R.drawable.xxx)
{
....your code
}

this solution is for who want to compare drawable id of imageview with id of drawable.xxx.

Tags:

Android