Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 814
Rohanil Avatar asked Oct 25 '25 04:10

Rohanil


2 Answers

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.

like image 93
konata Avatar answered Oct 26 '25 18:10

konata


Use:

int imageId = getResources().getIdentifier(inputId, "mipmap", getPackageName());

With "mimap", not "drawable" as the other answer suggests

like image 26
lil_matthew Avatar answered Oct 26 '25 16:10

lil_matthew