Search code examples
javaandroidimageandroid-imageview

Check what image is displayed in an ImageView?


So I know you can set the images of a ImageView like the following (assuming bun_picture is an ImageView):

bun_picture.setImageResource(R.drawable.rawbun);

but is there any way to check what image an ImageView is currently displaying? Something like (NOTE: .getImageResource doesn't exist, I'm just using it to get across what I want to do):

if(bun_picture.getImageResource() == R.drawable.rawbun) == true){
do something}

Obviously that doesn't work, but is there some equivalent I can use?

Thanks


Solution

  • Unless you have called mutate() on either of the drawables, you can check if two drawables represent the same image by comparing their ConstantState fields.

    ConstantState mine = bun_picture.getConstantState();
    ConstantState other = ContextCompat.getDrawable(context, R.drawable.rawbun).getConstantState();
    
    if (mine.equals(other)) {
        // they are the same
    }