Android set ImageView path dynamically as string - android

I have 10 images on /resources/drawable folder as following names;
pr1.gif, pr2.gif, ... pr10.gif
And I can easily set an image like this;
imgview1.setImageResource(R.drawable.pr5);
But I can't set it like following;
int pr = getpr(dm);
imgview1.setImageResource(R.drawable.pr + pr);
Is there a way to set it like this or should I use switch case?

You can get the id of a drawable by name using getIdentifier():
String prefix = "pr";
int suffix = getpr(dm); // I assume this returns the image number
Resources res = getResources();
int resId = res.getIdentifier(prefix + suffix, "drawable", "my.package.name");
imgview1.setImageResource(resId);
Note you can use this for any type of resource, whether it's drawable, string, array, etc. Just make sure you change the second parameter from "drawable" to the appropriate type.

Related

Android loading images to ImageView from drawable using only the file name

I need to load an image from drawable to an image view.
The ImageView is part of a ListViewItem, hence I have a large number of items and a large number of images.
When loading, the app parses a JSON file which states, among other information, the file name to be loaded per list item.
for example, "test_a.jpg".
The file "test_a.jpg" is located in "drawable".
I want, on runtime, to load drawable/test_a.jpg, test_b.jpg, big_chief.jpg and so on...
int intCurrImageResourceID = this.context.getResources().getIdentifier(strPictureName, "drawable", context.getPackageName());
any ideas on how to achieve that?
*** EDIT ****
It turns out that you shouldn't use file extension. So image.jpg is wrong. image is right. Thanks all. Especially #Augusto Carmo.
---- updated (correct answer)
A question, in your code, is strPictureName equals, for example, to something like this: "myDogPicture.png"? If yes, you should remove ".png" from the string first. Test it :) To get images from drawable with resource ids, you should not use the image extension.
---- old answer
You can achieve this with the following code:
// example - your ImageView
ImageView myImageView = (ImageView)findViewById(R.id.my_image_view);
// suppose the name of your image in drawable/ is my_image_name.jpg.
myImageView.setImageResource(R.drawable.my_image_name);
If you already know what the mapping between strings and resource ids will be, what do you think about using enum? example:
public enum MyImage{
CAT_IMAGE("cat.png", R.drawable.cat),
DOG_IMAGE("dog.png", R.drawable.dog),
HORSE_IMAGE("horse.png", R.drawable.horse);
private final String fileName;
private final int resId;
MyImage(String fileName, int resId){
this.fileName = fileName;
this.resId = resId;
}
/**
*
* #param imageFileName
* #return -1 if image not found
*/
public int getResId(String imageFileName){
int resId = -1;
for (MyImage myImage : MyImage.values()) {
if (imageFileName.equals(myImage.fileName)){
resId = myImage.resId;
break;
}
}
return resId;
}
}

Drawable Reference

I have few images in my app ( they are all copied into res/drawable and have appropriate R.drawable reference) that I want to assign them to my ImageViews using contents of an string type variable. To illustrated, I have an image file named "c4.png" in my drawable folder and an string variable (card) that contains "c4". I want to see if there is any way I can use a code like this (ImageView1.setImageResource(R.drawable.card)) to assign image c4 to my ImageView1 instead of using ImageView1.setImageResource(R.drawable.c4). Basically, I am wondering if it is possible to replace a variable with the specific image name in the R.drawable.resourceName. I know that R.drawable.resourceName is an integer and I am not trying to change its type. I want to replace the resourceName with a variable. I appreciate any help
Use this to draw a random number in particular range-
int min = 0;
int max = 9;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Then using this number pick image from image array-
public Integer[] nImages = {
R.drawable.c1, R.drawable.c2,
R.drawable.c3, R.drawable.c4,
R.drawable.c5, R.drawable.c6,
R.drawable.c7, R.drawable.c8,
R.drawable.c9, R.drawable.c10
};
ImageView1.setBackgroundResource(nImages [i1]);
Hope this works.
Try this
Resources res = getResources();
int id = res.getIdentifier(card, "drawable", getPackageName());
img.setImageResource(id);
this may solve your problem.
Or you can put the images in the asset folder. Assets are referenced by their filename, as in
getAssets().open(<filename>);
This returns an InputStream. Afterwhich it is trivial to convert them to a Bitmap resource
BitmapFactory.decodeStream(inputStream);
And then use that bitmap for your ImageView. That should be straightforward with
imageView.setImageBitmap(bitmap);
I want to replace the resourceName with a variable.
Instead of declaring the variable card as a string declare it as an Integer. So that you can use it like the following.
int card=R.drawable.c4;
ImageView1.setImageResource(card);
You probably can not do something like R.drawable.card because the R file is generated according to the resources in the drawable folder.
hope this helps

Android getResources/getIdentifier not returning ID

I have code like tthis:
String s = "replace__menu__" + data.imageid + ".png";
int RID = this.getApplicationContext().getResources().getIdentifier(s, "drawable-hdpi", getPackageName());
The String s = instruction sets a value that is the same as one of names in my res/drawable-hdpi folder. However, the returned value sets RID to the value 0
Any idea why my code is not working? Am I doing something wrong?
Try this
String s = "replace__menu__" + data.imageid; // image name is needed without extention
int RID = this.getApplicationContext().getResources().getIdentifier(s, "drawable", getPackageName());
".png" is not part of a ressource name
"drawable-hdpi" I would try just 'drawable' instead

Reference to R.drawabe dynamically?

I got about 200+ Country names in my app.
I got 200+ flag icons for each country.
The flag icons names are equals the country names, so like:
Country name: ENG, icon name eng.png
I want to make a list of them in my app to select country.
I dont want to build the layout by manually and add 200+ icons for each and every TextView...
My question is, can i add dynamically somehow ?
Something like this:
private void setIcon(String iconName)
{
countryIcon.setBackgroundResource(R.drawable. /* and i need the magic here*/ +iconName )
}
So can i reference to R.drawable dynamically by somehow with param?
Try this:
private void setIcon(String iconName) {
Resources res = getResources();
int imageResource = res.getIdentifier("drawable/" + iconName, null, getPackageName());
Drawable image = res.getDrawable(imageResource);
countryIcon.setBackgroundResource(image);
}
If you've a pattern, is not difficult at all.
Here's an example. I did this for loading flag-images in a ListView depending the flag IDs of each row-object. Once i've the language_id i get the language_KEY (String) which is the same as my icon's name:
int ico_id, int visible=View.visible();
String flag;
Bitmap icona;
flag= (MyWharehouse.getLangKey(language_id.get(position))).toLowerCase(); //get the image.png name
ico_id = a.getResources().getIdentifier(flag, "drawable", a.getString(R.string.package_str));
icona = BitmapFactory.decodeResource(a.getResources(), ico_id);
((ImageView)a.findViewById(R.id.im_lang_01)).setImageBitmap(icona); //changing the image

Android, reference things in R.drawable. using variables?

say I want to dynamically load an image file in R.drawable.* based on the value of a string
Is there a way to do this? It seems like I need to statically refer to anything in R.
Have you declared the id for the image in XML file? If you did, you can use the following method:
Let's say you have picture.png in your res/drawable folder.
In your activity, you can set your image resource in the main.xml file
<ImageView android:id="#+id/imageId" android:src="#drawable/picture"></ImageView>
In FirstActivity
//to retrieve image using id set in xml.
String imageString = "imageId"
int resID = getResources().getIdentifier(imageString , "id", "package.name");
ImageView image = (ImageView) findViewById(resID);
imageString is the dynamic name. After which you can get the identifier of the dynamic resource.
Another method, you can do this:
//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );
You will be able to reference your image resource and set your ImageView to it.
int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);
Try this. This should work.
Class res = R.string.class;
Field field = res.getField("x" + pos);
headerId = field.getInt(null);
header.setText(headerId);
this works with drawables as well, just edit the string. the header part is not required, it's just an example pulled from something I wrote a while ago.

Categories

Resources