0

I have an issue with grabbing an image dynamicly. Simply put, how can I do something like this:

ImageView img = (ImageView)findViewById(R.id.img_place);
img.setImageResource(R.drawable.image_string[1]);

So basicly, the image_string could hold anything,

image1 image2 image3

Must be possible, but can't figure out how.

2
  • what you want to implement exactly? Commented Oct 12, 2011 at 12:11
  • I think you're searching for that question. The answer explains how to get resources by a string. Commented Oct 12, 2011 at 12:12

3 Answers 3

3

You could do it like this,

public static Integer[] images = new Integer[]{R.drawable.my_love,R.drawable.first,R.drawable.second,R.drawable.third};

And then set the image resource like this,

ImageView mImageView = new ImageView(this.context);
mImageView.setImageResource(this.images[position]);
Sign up to request clarification or add additional context in comments.

Comments

3

You can get Resources by name. like this:

ImageView img = (ImageView)findViewById(R.id.img_place);
int resource = getResources().getIdentifier(image_string[0], "drawable", "com.package");
img.setImageResource(resource);

1 Comment

This is actually the best answer, surprised no one has upvoted yet.
0

Assuming that image_string was an XML string array, you could do the following:

String[] image_string = getResources().getStringArray(R.array.image_string);

And then access elements like a normal array.

However, setImageResource takes the ID of a resource, not a string.

So to get the ID, you would do something like:

ImageView img = (ImageView)findViewById(R.id.img_place);
String[] image_string = getResources().getStringArray(R.array.image_string);
img.setImageResource(getResources().getIdentifier(image_string[1] , "drawable", getPackageName()));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.