CLOSE ✕
Get in Touch
Thank you for your interest! Please fill out the form below if you would like to work together.

Thank you! Your submission has been received!

Oops! Something went wrong while submitting the form

Use Variables for Resource ID in Android

Neelanshi Sharma
|
Android
|
Jan 27, 2021

Resources class is for accessing an application's resources. This sits on top of the asset manager of the application (accessible through getAssets()) and provides a high-level API for getting typed data from the assets.

The Android resource system keeps track of all non-code assets associated with an application. You can use this class to access your application's resources. You can generally acquire the Resources instance associated with your application with getResources().

Implementation

1. Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

2. Add the following code to res/layout/activity_main.xml.

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MainFrame"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
   android:id="@+id/button1"
   android:layout_width="match_parent"
   android:layout_height="172dp"
   android:layout_x="12dp"
   android:layout_y="26dp" />

<Button
   android:id="@+id/button2"
   android:layout_width="match_parent"
   android:layout_height="172dp"
   android:layout_x="20dp"
   android:layout_y="184dp" />

</AbsoluteLayout>

3. Retrieve the resources from XML from .java file in the following way.

Button[] buttons;
for(int i=0; i<buttons.length; i++) {
{
  String buttonID = "button" + (i+1);

  int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
  buttons[i] = ((Button) findViewById(resID));
  buttons[i].setOnClickListener(this);
}

getIdentifier(String name, String defType, String defPackage)

1. name: The name of the desired resource.

2. defType: Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type.

3. defPackage: Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package.

This definition can be changed and used for different components or even for different resources.

For example:

int resID = getResources().getIdentifier(editTextID, "id", getPackageName());
int resID = getResources().getIdentifier(checkboxID, "id", getPackageName());
int resID = getResources().getIdentifier(resourceName, "drawable", getPackageName());
int resID = getResources().getIdentifier(resourceName, "array", getPackageName());
int resID = getResources().getIdentifier(resourceName, "color", getPackageName());

And many more customizations!!

Neelanshi Sharma
Neelanshi is a mobile and web developer. She is a computer science major from Banasthali Vidyapith, India.

Recent Blog Posts

Lets Work Together
Contact Me