Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawable == drawable?

This is my problem...:

In my activity I have an ImageView and a Button. I want the Button to perform an action ONLY when the ImageView displays a certain drawable. And yes, this means that the ImageView is animating between various drawables that is coded such that it does not interrupt with what I want done.

ImageView imgview = (ImageView)findViewById(R.id.imgviewsid);
Resources res = getResources();
Drawable acertaindrawable = res.getDrawable(R.drawable.thecertaindrawable);
Drawable variabledrawable = imgview.getDrawable();

    if (variabledrawable == acertaindrawable)
    {
            //does something
    }

It didn't work. And I've narrowed it down to the fault of the line "if (variabledrawable == acertaindrawable)". While Eclipse does not blatantly report errors that Android cannot recognize if two drawables are the same, I've tested the other areas of the code and all seem to work fine.

like image 713
sneak14 Avatar asked Dec 12 '10 07:12

sneak14


2 Answers

I know it's fairly late to post this, but it'll be useful for anyone googling.

I used .getConstantState() to compare my two drawables and it worked like a charm :)

like image 57
Toshinou Kyouko Avatar answered Oct 15 '22 10:10

Toshinou Kyouko


As explained by Itsik, even if both variables contain references to objects that 'look' the same, they are 2 different objects instances.

The == operator compares references. It returns true only if both variables refer to the same object instance ie. the same memory space.

Neither Drawable nor BitmapDrawable implement a specific .equals() method that could have been adapted to check that 2 instances contain the same data, so Mathias Lin hint to try .equals() will not work.

What you could do, following Itsik's advice without having to extend Drawable, is use the View.setTag() and View.getTag() methods. These methods allow to attach any Object of your choice to a View and retrieve it later. By attaching a simple identifier (be it a technical integer identifier or a url defining the source of the bitmap) to your ImageView each time you change its content, you will be able to recognize it easily.

like image 40
Kevin Gaudin Avatar answered Oct 15 '22 11:10

Kevin Gaudin