0

I have an children's app with a large number of ImageButtons, each ImageButton displays a different, randomly-chosen animal image. When the app says, "Which one is the Monkey?" the child hopefully pushes the ImageButton with the monkey image.

To do this, however, I need code that can compare the image within the ImageButton to the target bitmap image in R.drawable. Previous posts here on StackOverflow have suggested that the solution to this problem is to set tags in the ImageButtons, but that is not a feasible solution here, for reasons too long to explain.

Here's my code thus far:

private boolean compareImages(ImageButton buttonPushed){
    Drawable drawable = buttonPushed.getDrawable();
    if(drawable.getConstantState().equals(R.drawable.monkey))     // NOT WORKING
        return true;
    return false;
}

In the debugger, I can see the equals() line fail, but I'm not sure why. I'm also not sure I'm comparing the same things, either. From reading up on other StackOverflow posts, it looks like the way to inspect the bitmap is with this:

    Drawable drawable = buttonPushed.getDrawable();
    drawable.getConstantState()    <--- this points to R.drawable.monkey ???

Not sure. Anyone know the syntactic secret?

Pete
  • 1,511
  • 2
  • 26
  • 49

1 Answers1

1

From a previous question that very similar here.

Try this

if(drawable.getConstantState().equals(getResources().getDrawable(R.drawable.monkey).getConstantState())){
       //Do your work here
    }
ITried
  • 429
  • 3
  • 12
  • I'm afraid that didn't work... although if I break out the two getConstantState() calls into their own separate lines and then watch them in the debugger, they are plainly returning the same object. Maybe using equals() is not the way to go...? – Pete Dec 04 '17 at 03:58
  • Really? I just tried it and it worked for me. How did you set the drawable as the background for the ImageButton? For me, android:background="@drawable/image" didn't work but android:src="@drawable/image" fixed the issue. Maybe that's what you're doing? – ITried Dec 04 '17 at 04:15
  • I tried again, this time writing a separate getResources().getDrawable(R.drawable.animal).getConstantState() line for every animal image in my R.drawable library. This time it worked. I'm not sure what I was doing wrong yesterday, but there's no doubt it is working now. Sorry about that - I should really stop trying to code in these 12-hour stretches. Many thanks!!! – Pete Dec 04 '17 at 13:39