How to Get Resource Name From Resource ID in Android?
In Android, the resource name is the name assigned to a resource while declaring it in the code or in the XML. The resource name is of format:
- <package_name> is the name of the package where the resource is stored
- <resource_type> is R subclass for the type of resource (drawable, string, color, etc)
- <resource_name> is the name of the resource if declared in the layout element (android: name) or a file name without an extension
Below is how we declare a resource in the code and in XML:
- In the code: R.string.geeksforgeeks
- In XML: @string/geeksforgeeks
In this article, we will show you how you could fetch the resource name using the resource id.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Button and a TextView in the layout file.
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Get resource id and fetch and display the resource name on button click.
You can see that on button click, the resource name is displayed in the TextView.
Please Login to comment...