Search code examples
javaandroidmipmaps

is it possible to get mipmap image by id?


I have stored image icons in res/mipmap folder of my android project. Each of them have their own image id. I want to check if I have image there by image id. I want to do something like,

String input_id = "blue_image";
ImageView image;
if (image.getImageByID(input_id)){  ## if image with blue_image exists
    image.setImageResource(...);
}

If I know that blue_image exists then I usually get it like

image.setImageResource(R.mipmap.blue_image);

There seems to be 2 problems in this question. One is about checking image exists by ID and second one is to find something similar to getattr() python function in java.

If you have any other solutions to similar case, those are also welcome.


Solution

  • Try this in your Activity class:

    int imageId = getResources().getIdentifier(inputId, "drawable", getPackageName());
    
    if (imageId > 0) {
        image.setImageResource(imageId);
    }
    

    The point is that getIdentifier() returns 0 if no resouce was found.