[JAVA] Code to specify the image name as a character string and paste it into ImageView (android)

With swift, you can specify the image by the image name and paste it, but by the way, it was not android (Is it there?)

I couldn't find it, or I didn't really look for it, but I made it somehow.

The procedure is ① Get the resource ID from the image name ② Set the image using the resource ID Only this.


public void setBackgroundResourceByString(Context context, String imgName, View view){
    int resourceId = context.getResources().getIdentifier(imgName, "drawable", context.getPackageName());

Substitute the context obtained by getContext () etc. as the first argument, The second argument is to substitute the image name put in drawable as a string type, Substitute the imageView or View with the image pasted as the third argument.

I feel a little sick


public int getResourceIdByString(Context context, String imgName){
    return context.getResources().getIdentifier(imgName, "drawable", context.getPackageName());

A method like this may be safe

By the way, maybe drawable can also get the resource ID of colors and characters registered as color and string.

Recommended Posts

Code to specify the image name as a character string and paste it into ImageView (android)
Get an image as a character string (resource name) and paste it into ImageView (kotiln)
[Android] How to convert a character string to resourceId
[Android development] Get an image from the server in Java and set it in ImageView! !!
How to specify character code and line feed code in JAXB
Memorandum No.4 "Get a character string and decorate it" [Java]
[Code golf] Deflate the code and submit it to AtCoder [Compressed golf]
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
Read the file under the classpath as a character string with spring
How to read a file and treat it as standard input
Invoke the character string passed as an argument as a method with send
Add the pre-built jar library to Android and call it in the framework
A shell script that builds a Docker image and pushes it to ECR
Is it possible to put the library (aar) in the Android library (aar) and use it?
The Android app crashes. Just click a button and it will fall.
[Ruby] I want to make an array from a character string with the split method. And vice versa.
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.