Home > Java > javaTutorial > How Can I Get Android Resource IDs Using Their Names?

How Can I Get Android Resource IDs Using Their Names?

Susan Sarandon
Release: 2024-12-23 09:32:28
Original
900 people have browsed it

How Can I Get Android Resource IDs Using Their Names?

Retrieve Resource Ids Using Resource Names

Accessing resources such as strings and drawables by their names instead of their integer IDs is sometimes necessary.

Method:

To achieve this, use the getIdentifier() method of the Resources class. The following code sample demonstrates obtaining a drawable resource ID by its name:

int drawableResourceId = getResources().getIdentifier("nameOfDrawable", "drawable", getPackageName());
Copy after login

This method can also be used to obtain IDs for other resource types, such as strings and UI elements:

// String resource
int stringResourceId = getResources().getIdentifier("nameOfString", "string", getPackageName());

// UI element ID
int viewId = getResources().getIdentifier("nameOfView", "id", getPackageName());
Copy after login

Caution:

Note that using this method for resource retrieval is relatively slow, so it should be used sparingly. For performance-sensitive applications, it's recommended to use integer IDs instead.

Reference:

Resources.getIdentifier(String name, String defType, String defPackage) documentation: https://developer.android.com/reference/android/content/res/Resources#getIdentifier(java.lang.String, java.lang.String, java.lang.String)

The above is the detailed content of How Can I Get Android Resource IDs Using Their Names?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template