hakki
hakki

Reputation: 6521

Creating Dynamic R.drawable source and ImageView

I have an Activity which has variable position that comes from another activity. I handle this variable with Intent like below. (Actually position is listView's position from another activity.) and values of position variable are 0 to 200

I took my Extra, then assigned it to a string than I parsed it to an Integer. These are normal and easy for me and working.

Intent i            = getIntent();
String position     = i.getStringExtra("POSITION");
int position_to_int = Integer.parseInt(position);

But my problem is about resources.

Simply I want to put an image to my LinearLayout dynamically . I have some country flags and they named in format like 0.gif, 1.gif, 2.gif, 3.gif ...

My idea is using position variable's value for this purpose.

but when I try to use position_to_int variable for name of flag, Eclipse returning error normally. Because R.drawble.XXX values storing in R.java

ImageView imageView = new ImageView(this);
// setting image resource
imageView.setImageResource(R.drawable.position_to_int);

How can I use position_to_int variable to show an ImageView dynamically?

Upvotes: 1

Views: 2772

Answers (1)

Raghav Sood
Raghav Sood

Reputation: 82553

You can't access it directly. You'll have to get the resource using its name:

private Drawable getDrawableResourceByName(int name) {
    String packageName = getPackageName();
    int resId = getResources().getIdentifier("character_you_prefixed" + String.valueOf(name), "drawable", packageName);
    return getResources().getDrawable(resId);
}

Note that your resource names must begin with a letter, not a number, or else your project will not compile. Try adding a character to the beginning of each file name.

Upvotes: 3

Related Questions