First of all, Resources.getDrawable(int)
is deprecated. It is probably not related to your problem, but you should fix it.
If you compare bitmaps using ==
you are comparing object identities. If the ==
test is giving you false
, that means you are comparing different objects. There can be no doubt about that.
Your snippets don't give enough context to be sure, but here are some possibilities:
Something in your code is causing a different value to be assigned to bitred
.
The bitred
identifiers in the two snippets of code do not denote the same Java variable.
Your assumption that the "red" bitmap that is being used as a red background will always be the same object is invalid.
Lets assume that you have already eliminated 1. and 2. above, and focus on 3. How could that happen? Well, we can't see the relevant code (where you randomly swap the button images) but I can think of a couple of possibilities:
- You could be fetching the bitmap from
Resources
repeatedly.
- The method you call to switch the bitmaps could be creating / setting a copy.
- The method you call to get the clicked button's bitmap could be returning a copy.
And since each of the above operations could depend on API implementations that could behave differently (because the javadoc allows that) the behavior of your app can be platform dependent.
So what is the solution?
Hypothetically, if you can figure out what is causing different bitmap objects to be used, you could potentially work around it. However, while your code still relies on unspecified behavior, there is a risk that it will break on other phones ...
A better solution is to change your app so that DOES NOT rely on using ==
to compare Bitmap
objects. For example:
Associate a tag with each button.
button1.setTag("one");
button2.setTag("two");
Create a HashMap
that maps from a button's tag to the current color for that button. The HashMap is part of the app's "model" state.
Map colors = new HashMap();
...
colors.put("one", "red");
colors.put("two", "blue");
When you change the image bitmaps for the buttons, make the corresponding update to the map.
// After swap the images of button1 and button2 ...
String c1 = colors.get("one");
String c2 = colors.get("two");
colors.put("one", c2);
colors.put("two", c1);
In the onClick method, use the map to lookup the button's current color rather than attempting to figure it out by comparing Bitmap
objects.
if (colors.get(v.getTag()).equals("red")) {
// it is red!
}
(Note that this is close to what Biju Parvathy suggests, but he hasn't said explicitly how to deal with the button colors / images changing.)