Compare two drawables [duplicate]

0

Whenever I click on my ImageButton I want to compare the image of it with the drawable I have in the resources.

imag.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

    ImageButton photo = (ImageButton)view;

            Drawable imagem= photo.getBackground();
            Drawable cartOff = getContext().getResources().getDrawable(R.drawable.cart_off);
            Drawable cart = getContext().getResources().getDrawable(R.drawable.cart);


            if(imagem.equals(cart))
            {
                Toast.makeText(getContext(), " certo", Toast.LENGTH_SHORT).show();
            }
            if(imagem.equals(cartOff))
            {
                Toast.makeText(getContext(), " errado", Toast.LENGTH_SHORT).show();
            }
        }
    });

But it is not working, it does not return any of the Toasts

    
asked by anonymous 19.05.2017 / 11:50

1 answer

1

You are creating different instances of your drawable and comparing them, they will never be the same because they are allocated in different memory addresses.

Use the getConstanteState method to perform this comparison.

getContext().getResources().getDrawable(R.drawable.cart_off).equals(photo.getBackground().getConstantState())
    
19.05.2017 / 12:26