Dynamically obtain the corresponding resource id based on a resource name, dynamically corresponding to the resource id
In the process of project creation, a requirement is met. In the Android code, images can be dynamically loaded using the image ID. To load the image in the Android folder, we need to know its ID. to dynamically obtain the image ID, we need to dynamically obtain the image ID.
So what should we do?
Resources res=getResources();String packageName =getPackageName();imageView.setImageBitmap(BitmapFactory.decodeResource(res,res.getIdentifier(pracData.getQuestion(),"drawable",packageName)));
We can use
Res. getIdentifier (String str, "drawable", packageName) to obtain the image ID.
If stris the image name and the title is a.png, str is.
Drawable is the folder for storing images.
PackageName is the package name of the activity.
Next, let's talk about how to dynamically obtain other resource IDs.
1. Get the layout resource ID
Int layoutId = getResources (). getIdentifier ("activity_main", "layout", getPackageName ());
2. obtain image resources (in the mipmap file)
Int mipmapId = getResources (). getIdentifier ("ic_launcher", "mipmap", getPackageName ());
3. Get character Resources
Int stringId = getResources (). getIdentifier ("author", "string", getPackageName ());