2

How can i access an Adroid drawable by a variable? Example I have drawables :[ logo1.png logo2.png ... logoN.png]; Is there a way so i can do that?

String logopicker="1";
logo.setImageResource(R.drawable.**logo+logopicker**);

Well i know this code will never run but you get the idea of what i want to do. Thank you

1 Answer 1

17

This code is running for me successful (I have already used in my one of the application), You can Try this:

     cnt=1;

     String icon="logo" + cnt;
     int resID = getResources().getIdentifier(icon, "drawable",  getPackageName()); 
     logo.setImageResource(resID); 

     cnt++;  // this require if you want to set images in loop

Enjoy !!

4
  • 1 sec before you replyed i found the answer from the api. Nevertheless thank you very much.
    – weakwire
    Jul 10, 2010 at 8:56
  • sorry thought that marked as correct is enough (i'm new here :D)
    – weakwire
    Jul 10, 2010 at 9:05
  • getResources and getPackageName requires context Mar 22, 2022 at 21:17
  • use of getIdentifier is discouraged because resource reflection makes it harder to perform build optimizations and compile-time verification of code Jan 24 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.