Home > Java > javaTutorial > How to Efficiently Get an Android Resource ID from its String Name?

How to Efficiently Get an Android Resource ID from its String Name?

DDD
Release: 2024-12-20 09:31:09
Original
561 people have browsed it

How to Efficiently Get an Android Resource ID from its String Name?

Getting Resource ID from String in Android

When passing a resource ID to a method, it's often desirable to access both the ID and the corresponding string. For instance, consider the "icon" resource:

R.drawable.icon
Copy after login

To obtain both the ID and the string "icon", several approaches can be explored:

One solution involves utilizing the Resources.getIdentifier() method:

int resID = getResources().getIdentifier("icon", "drawable", getPackageName());
String iconString = "icon";
Copy after login

However, recent research has indicated that Resources.getIdentifier() can be less efficient than using reflection.

Alternatively, you can employ the following reflection-based code:

public static int getResId(String resName, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(resName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}
Copy after login

To utilize this method for the "icon" resource:

int resID = getResId("icon", R.drawable.class); // or other resource class
String iconString = "icon";
Copy after login

Although this reflection approach may be more efficient, it's important to note potential drawbacks. In a release build with code/resource shrinking enabled, this solution may fail. Additionally, it might not work in cases where the string name differs from the expected resource name format.

The above is the detailed content of How to Efficiently Get an Android Resource ID from its String Name?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template