Reputation: 473
I want to change the image resource for bitmap dynamically. But I can't call them with name from the drawable class.
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.getImage(foldername + "/" + imagename));
I need to do something like that but I couldn't find the proper way of doing this.,
EDITED
I think I should be more clear. I store my images under the drawable folder and they are separeted into other folders.
For example;
drawable/imageset1, drawable/imageset2,
and I want to change the Image resource for bitmap depending on user input.
For example: User selects imageset5 from first spinner, and selects image5.png from another spinner.
Upvotes: 0
Views: 1563
Reputation: 3370
Just try following: Your image having name "imagename" must be in the folder
String IMAGE_FOLDER_NAME = "YOUR_IMAGE_CONTAINING_FOLDER";
Now, use following code:
String imagename = "YOUR_IMAGE_NAME";
String PACKAGE_NAME=getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":"+IMAGE_FOLDER_NAME+"/"+imagename , null, null);
System.out.println("IMG ID :: "+imgId); // check this in log
System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME); // check this in log
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId);
Upvotes: 0
Reputation: 6115
I hope this will do what you want
BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(foldername + "/" + imagename , "drawable", getPackageName());
EDITED:
while the above code will work only if you follow android rule which doesn't allow sub directories in drawable folder so the above code will work only when directly accessing images from drawable.
BitmapFactory.decodeResource(getResources(), getResources().getIdentifier( imagename , "drawable", getPackageName());
As these links describe
How to access res/drawable/"folder"
Can the Android drawable directory contain subdirectories?
Upvotes: 2
Reputation: 1791
you can't do like this. You have to add all images in drawable & use it like
myImage.setBackgroundResource(R.drawable.imageName)
or after downloading the image from web you can apply as
myImage.setBitmap(BitmapFactory.decodeStream(in));
to get the bitmap where in is InputStream
Upvotes: 0
Reputation: 4960
Is it a resource stored in the drawables folder? Then try this method from BitmapFactory
public static Bitmap decodeResource (Resources res, int id)
Where
res = getResources()
and id is the id of the drawable like
R.drawable.picture
Check it out here
Upvotes: 0
Reputation: 15847
Make one array of image resources
int []a = int[]
{
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.four,
};
Then access it in loop
for(int i=0;i<a.length;i++)
{
// a[i]
}
Upvotes: 0