How to get Resource(int) from String - Android

12,476

Solution 1

Use this to get resource id:

int picId = getResources().getIdentifier(picName, "drawable", getApplicationContext().getPackageName());

Solution 2

If you want to get the integer then simply remove the quotes.

int id = R.drawable.image1; // instead of "R.drawable.image1"

That will give you the number.

Solution 3

View view = findViewById(R.drawable.image1);
int id = view.getId();
Share:
12,476
Saruulbat
Author by

Saruulbat

Updated on July 27, 2022

Comments

  • Saruulbat
    Saruulbat almost 2 years

    Possible Duplicate:
    Android, getting resource ID from string?

    String res = "R.drawable.image1";
    

    I need to get it's INT id. Please help me!

  • Mohammed Azharuddin Shaikh
    Mohammed Azharuddin Shaikh about 12 years
    there is nothing method like getApplicationPackageName(), without seeing the answer how one can upvote, ahh.
  • Nishant
    Nishant about 12 years
    sorry my fault I have updated the answer
  • OneCricketeer
    OneCricketeer almost 8 years
    This returns R.drawable.image1... You used an id you already had, then found it, then get it back
  • Alejandro
    Alejandro almost 8 years
    This does not answer the question of retriving an Id using a string because you hardcode it in findViewById