开发者

drawable == drawable?

开发者 https://www.devze.com 2023-01-29 22:32 出处:网络
This is my problem...: In my activity I have an ImageView a开发者_JAVA百科nd a Button. I want the Button to perform an action ONLY when the ImageView displays a certain drawable. And yes, this means

This is my problem...:

In my activity I have an ImageView a开发者_JAVA百科nd 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.


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 :)


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.


Try if (acertaindrawable.equals(variabledrawable)) ...


variabledrawable and acertaindrawable aren't the same Object, even though they might display the same drawable.

If android doesn't give you a built-in way to compare drawables (i guess it depends on the concrete drawable you have), my advice to you is to Extend the Drawable class that you are using and add a private field that holds some kind of ID so that you can compare between drawables.


you can also try:

getId() and setId() :=)

can also be used for comparision if tags are already used for something else :)

Ps.: but watch out if you're using RelativeLayouts ... :=P

0

精彩评论

暂无评论...
验证码 换一张
取 消