Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic loading of images R.Drawable using variable

Tags:

android

I think i'm getting closer but still getting resource errors with this. I have an image file named rock.png in all 3 drawable folders.

in my layout MAIN.XML:

 <ImageView android:id="@+id/rockId" android:src="@drawable/rock"></ImageView>

In my code:

            int resID = getResources().getIdentifier("rockId" , "id", "com.testing");
            ImageView image = (ImageView) findViewById(resID);

I'm still seeing this in my error catlog:

10-30 17:36:24.485: WARN/ResourceType(74): Resources don't contain package for resource number 0x7f020000

Any thoughts on what I might be doing wrong? Any tips welcome

like image 592
RandomUser Avatar asked Oct 30 '11 21:10

RandomUser


1 Answers

to find the control:

ImageView image = (ImageView) findViewById(R.id.rockId);

To dynamicly load an image from drawable i use this function

    public static int getDrawable(Context context, String name)
    {
        Assert.assertNotNull(context);
        Assert.assertNotNull(name);

        return context.getResources().getIdentifier(name,
                "drawable", context.getPackageName());
    }

this will return the id of your drawable, now all you need to to is set the image in the control:

image.setImageResource(int Id);
like image 197
Pedro Rainho Avatar answered Oct 29 '22 12:10

Pedro Rainho