Home >Java >javaTutorial >How to Efficiently Retrieve Android Resource IDs and String References from a String?

How to Efficiently Retrieve Android Resource IDs and String References from a String?

DDD
DDDOriginal
2024-12-20 12:56:141043browse

How to Efficiently Retrieve Android Resource IDs and String References from a String?

Getting Resource ID and String Reference from a String

Many Android development scenarios require passing both the resource ID and the corresponding string to methods. For instance, you may encounter a reference like R.drawable.icon and require both its integer ID and the string "icon".

Solution 1: Using Resources.getIdentifier()

Android Studio provides an efficient method known as Resources.getIdentifier(). This function takes the string, package name, and resource type as parameters and returns the corresponding resource ID. The package name can be obtained using getPackageName(). For the example in question, the code would be:

int resId = getResources().getIdentifier("icon", "drawable", getPackageName());
String resString = "icon";

Solution 2: Using Reflection

Prior to Android Studio's introduction of Resources.getIdentifier(), reflection was commonly used to achieve this functionality. The following code demonstrates this approach:

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;
  }
}

It can be utilized as follows:

int resId = getResId("icon", R.drawable.class);
String resString = "icon";

Performance Considerations

According to some sources, Resources.getIdentifier() performs faster than the reflection-based approach. However, it's important to note that the reflection method may fail in certain Android build scenarios, particularly when code and resource shrinking are enabled.

The above is the detailed content of How to Efficiently Retrieve Android Resource IDs and String References from a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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