Reputation: 1478
I am trying to make images dynamic in my android application. With the help of other posts i wrote this code but i am unable to set image resource. Here is my code.
// get image whose source i want to change..
ImageView IV = (ImageView) findViewById(R.id.imageView1);
// x for 1,2,3.. hangman1.png,hangman2.png and so on image are located
// under res/drawable-mdpi
int j = getResources().getIdentifier("hangman"+x, "imageView", getPackageName());
// here i get errork, The method setImageResource(int) in the type ImageView
// is not applicable for the arguments (Drawable)
IV.setImageResource( getResources().getDrawable(j) );
Upvotes: 3
Views: 5666
Reputation:
from your xml file , use app:src instead of android:background, and from the activity file, use :
setImageDrawable(getRessource().getDrawable(R.drawable.yourRessource));
Upvotes: 0
Reputation: 134664
Because you're trying to pass in a Drawable. getDrawable(), as its name states, returns a Drawable object. setImageResource takes a resource ID, which is what getIdentifier will return. You should just pass j
to setImageResource()
.
Edit: Heh, and you also should use Yashwanth's answer, as he said. :)
(TEAMWORK!)
Upvotes: 4
Reputation: 1478
combining both above solutions did the trick for me..here is code.. dnt know which answer i should accept..
ImageView IV = (ImageView) findViewById(R.id.imageView1);
int j = getResources().getIdentifier("hangman"+x, "drawable", getPackageName());
IV.setImageResource( j );
Upvotes: 2
Reputation: 29121
int j = getResources().getIdentifier("hangman"+x, "drawable", getPackageName());
try this, if you are trying to get a drawable. and also as kcoppock said , just use j.
Upvotes: 13