android: Variable passed for R.drawable.variableValue - android

iv.setImageResource(R.drawable.icon);
this line is working good for me
can I pass a variable value instead of icon
like if i have 10 images in drawable and i want to decide on runtime which image to show
can i pass the value through a variable and work it like
String variableValue = imageName;
iv.setImageResource(R.drawable.variableValue);

Resources.getIdentifier() can solve your problem.
String variableValue = imageName;
iv.setImageResource(getResources().getIdentifier(variableValue, "drawable", getPackageName()));

You could use an array to define your drawables:
int[] images = new int[2];
images[0] = R.drawables.image1;
images[1] = R.drawables.image2;
And then you can use this array to set a image at runtime:
lv.setImageResource(images[i]);
Where is is in this case either 0 to point to the first image or 1 to point to the second image of the array.

No, it won't work that way.
In your first line icon is a generated static final member of the static final class R.drawable so trying to concatenate it up like it was a String would give you a compiler error.
But you could try using
iv.setImageURI(uri);
where uri is the URI to your image, so you can use a string value here.
Also, according to the api documentation, it would be a better solution to use setImageBitmap: you should consider it based on your resources.
APIDocs:
public void setImageURI (Uri uri)
Since: API Level 1
Sets the content of this ImageView to
the specified Uri.
This does Bitmap reading and decoding
on the UI thread, which can cause a
latency hiccup. If that's a concern,
consider using
setImageDrawable(Drawable) or
setImageBitmap(Bitmap) and
BitmapFactory instead.
Parameters
uri The Uri of an image

Related

Jetpack Compose how do i work with images when variable changes?

I use the composable function image. I need to use the specific image depending on the variable it gets.
it looks like the code underneath when hardcoded and this works for the specific image.
Image(
painterResource(id = R.drawable.carrot),
contentDescription = "carrot",
)
The problem is i want it to work like the picture below where recipe.image changes depending on what it gets from the database.
Image(
painterResource(id = recipe.image),
contentDescription = "recipe.name",
)
Somehow it needs the exact path to the drawable that is saved localy.
What i have tried:
I've tried to upload R.drawable.carrot directly to the database as an Integer, it saves it as something like 2400440340, when this integer gets into the painterResource it crashes.
I've tried to save the "R.drawable.carrot" directly as a string into the database but that don't work either because the painter needs an integer.
The only suggestions i can find to this problem on this site is this answer from 11 years ago:
int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);
I can't seem to find the functions getResources or the getIdentifier.
What i have tried: I've tried to upload R.drawable.carrot directly to the database as an Integer, it saves it as something like 2400440340, when this integer gets into the painterResource it crashes.
It crashes because this Int value in Resources is just a runtime reference, which means if you restart the app, the Resource, for example R.drawable.carrot, gets new referenced.
If you want another image in your painterResource, you have to change the value of recipe.name somewhere or you save your image binaries in the database (which is not very performant, I recommend not to do that).
You can load them over assets:
If you dont't have an assets folder, creat one in this location:
app/src/main/assets/
And then you can access it with a function like this:
fun getImageFromAssets(imageName: String): Bitmap {
val imageStream = assets.open(imageName)
val bitmap = BitmapFactory.decodeStream(imageStream)
imageStream.close()
return bitmap
}
Android Studio will suggest you to "Inline" the variable but don't do that. If you Inline the BitmapFactory at the return point, you close the Stream before you decode it.
You can now simply call the name from the database like:
val image: Bitmap = getImageFromAssets("imageName.jpg")

Refer to id of views dynamically with template strings?

(I'm sorry if I didn't use the correct term in the title.)
I have many widgets of ImageView with ids of image1, image2, image3, etc.
I would like to refer to one of them (for example image2) dynamically using an integer, something like:
val position = 2
image{position}.x = ....
Is such thing possible in Kotlin/Android? I'm only trying this direction since I know it's possible in JavaScript
You can use getIdentifier to get the identifier of your images like so:
int resId = context.resources.getIdentifier(
"image${position}",
"drawable",
context.packageName
);
or to get ids of image views like so:
int resId = context.resources.getIdentifier(
"image${position}",
"id",
context.packageName
);
Once you have the id's you could load drawables or views how you normally would with findViewById(resId) or ContextCompat.getDrawable(context, resId)
Make sure to call findViewById() on the parent of the view you are trying to find.

Can't dynamically change ImageView by code

I would like to understand, why I can't dynamically change the drawable resource from my imageView.
I have different use cases, and in function of these use cases I have to change my imageView. In my code I tried these solutions below, but I can't get my imageView refresh. It keeps the default drawable resource defined first. Here what I tried:
int imgRes = activity.getResources().getIdentifier("packageName:drawable/"+"my_drawable_name", null, null);
OR
int imgRes = activity.getResources().getIdentifier("drawable/"+"my_drawable_name", "drawable", activity.getPackageName());
imageIcon.setImageResource(imgRes);
imageIcon.invalidate();
And also:
imageIcon.setImageDrawable(null);
imageIcon.setImageDrawable(activity.getResources().getDrawable(R.drawable.my_drawable_name));
imageIcon.invalidate();
I'm in one adapter and I passed this ImageView from my activity to my adapter. And I'm doing this operation from this adapter which go the instance of my imageView.
So I tried to change this resource my_drawable_name but in both cases above, my imageView is never updated/refresh, and its image resource doesn't change. I have no error it just doesn't work. Am I doing something wrong ? What's the best practice to dynamically change a resource from an imageview by code?
No need to append drawable directory. It is the default behavior of android to get best suited drawable according to device.
Try using following code:
int imgRes = activity.getResources().getIdentifier("my_drawable_name", "drawable", activity.getPackageName());
try imageIcon.setImageResource(R.drawable.my_drawable_name);

can BitmapFactory.decodeResource(context,int) take context string

I have a method that returns a String(let's say the var sprite) and this string is the name of my bitmap img,and i want to use it with BitmapFactory.decodeResource() but i don't know how to combine this since it must be int R.drawable.sprite
Can this be done?
Yes, it's possible. Take a look at this question:
Android and getting a view with id cast as a string

How pass an image resource from my app to another?

I have 2 apps running, and I need to pass an image resource from the first app to the second.
The ImageView have a setImageURI(Uri) method, that I could use in the second app, but does not have a getUri() for me to use in the first.
Any idea how to do this?
-- update
looks like Content Providers can solve the problem. (studying)
The only way is to pass the data to the second Activity when you start it. If you check out the Intent API you can pass the Uri using one of the putExtra() methods, and in the onCreate for the new Activity you can retrieve the Uri using getStringExtra().
You can pass a (Bitmap)Drawable this way:
// sending side
BitmapDrawable bd = (BitmapDrawable)imageView.getDrawable();
intent.putExtra("img", bd);
// receiving side
Bitmap b = (Bitmap) intent.getParcelable("img");
imageView.setImageBitmap(b);

Categories

Resources