Android studio Android Studio-如何将Drawable中的图像与R中的其他Drawable进行比较?

Android studio Android Studio-如何将Drawable中的图像与R中的其他Drawable进行比较?,android-studio,bitmap,android-resources,android-imagebutton,Android Studio,Bitmap,Android Resources,Android Imagebutton,我有一个带有大量ImageButton的儿童应用程序,每个ImageButton显示一个不同的随机选择的动物图像。当应用程序说“哪只是猴子?”孩子满怀希望地按下带有猴子图像的ImageButton 然而,要做到这一点,我需要能够将ImageButton中的图像与R.drawable中的目标位图图像进行比较的代码。以前关于StackOverflow的文章建议解决这个问题的方法是在ImageButtons中设置标签,但这不是一个可行的解决方案,原因太长,无法解释 以下是我迄今为止的代码: priva

我有一个带有大量ImageButton的儿童应用程序,每个ImageButton显示一个不同的随机选择的动物图像。当应用程序说“哪只是猴子?”孩子满怀希望地按下带有猴子图像的ImageButton

然而,要做到这一点,我需要能够将ImageButton中的图像与R.drawable中的目标位图图像进行比较的代码。以前关于StackOverflow的文章建议解决这个问题的方法是在ImageButtons中设置标签,但这不是一个可行的解决方案,原因太长,无法解释

以下是我迄今为止的代码:

private boolean compareImages(ImageButton buttonPushed){
    Drawable drawable = buttonPushed.getDrawable();
    if(drawable.getConstantState().equals(R.drawable.monkey))     // NOT WORKING
        return true;
    return false;
}
在调试器中,我可以看到equals()行失败,但我不确定原因。我也不确定我是否在比较同样的东西。从其他StackOverflow文章中读取,检查位图的方法似乎如下所示:

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

getConstantState()来自上一个非常类似的问题

试试这个

if(drawable.getConstantState().equals(getResources().getDrawable(R.drawable.monkey).getConstantState())){
       //Do your work here
    }

恐怕那没用。。。尽管如果我将两个getConstantState()调用分成各自的行,然后在调试器中观察它们,它们显然返回了相同的对象。也许使用equals()不是最好的方法…?真的吗?我刚试过,它对我有效。您是如何将drawable设置为ImageButton的背景的?对我来说,android:background=“@drawable/image”不起作用,但是android:src=“@drawable/image”修复了这个问题。也许这就是你要做的?我再试了一次,这次为我的R.drawable库中的每个动物图像分别编写了一行getResources().getDrawable(R.drawable.animal).getConstantState()。这次成功了。我不确定我昨天做错了什么,但毫无疑问,它现在起作用了。很抱歉,我真的应该停止在这12个小时内编写代码了。非常感谢!!!