Ruchir Baronia Ruchir Baronia - 7 months ago 45
Android Question

Why is this not working sometimes?

TL;DR I have many buttons, and I am swapping the images of them. For some reason, my code only works on certain phones, and not on others.

My app uses the following code to compare images on imagebuttons:


redsquare = getResources().getDrawable(R.drawable.redsquare);
bitred = ((BitmapDrawable) redsquare).getBitmap();


is the button clicked)

ClickGround = v.getBackground(); //Get the background of button clicked
//the bitmap background of the button clicked
BitClick = ((BitmapDrawable) ClickGround).getBitmap();

Then, later on in the onClick, I check if the user clicked on the redSquare by doing this:

if (BitClick == bitred) { //Make sure it is the red square that user clicked

I have tested it on my emulator and HUAWEI phone, and it works fine. When I tested it on my other phone (lg g3), the if statement doesn't go through. Why are the results different? Is the image somehow being messed up in my phone?


You Can, I'm making a small change in your comparison code to make it work with all devices.

Bitmap BitRed = ((BitmapDrawable)getResources().getDrawable(R.drawable.redsquare)).getBitmap();

Bitmap BitClick = ((BitmapDrawable) v.getBackground()).getBitmap();

if (BitClick.sameAs(BitRed)) 
    //Your Button with Red Square Clicked

Please refer SameAs function for more details. Hope this help you.