Compare two drawables

Asked

Viewed 130 times

0

Every time I click on my Imagebutton I want to compare his image with the drawable I have in 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();
            }
        }
    });

Only it’s not working, not returning any of the Toasts

1 answer

1

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

Use the method getConstanteState to make this comparison.

getContext().getResources().getDrawable(R.drawable.cart_off).equals(photo.getBackground().getConstantState())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.