Open In App

How to Get Resource Name From Resource ID in Android?

Last Updated : 11 Aug, 2021
Like Article

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.


<?xml version="1.0" encoding="utf-8"?>
    <!-- We shall find the resource name of this Button -->
    <!-- Also, if we click this button, we shall get 
         the desired results in the TextView below -->
    <!-- This TextView shall display the resource name
          when the above button is clicked -->

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.


import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // Declaring and initializing the button
        // and text view from the layout file
        val mButton = findViewById<Button>(
        val mTextView = findViewById<TextView>(
        // Fetching the id of the button (resource
        val resourceId =
        // Getting the name of the resource
        val resourceName = resources.getResourceName(resourceId)
        // When button is clicked, the text view
        // will display the value of resourceName
        mButton.setOnClickListener {
            mTextView.text = resourceName.toString()


You can see that on button click, the resource name is displayed in the TextView.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads