12

there are many images in drawable foder so instead manually creating array of all image resource ids , i want to get all images dynamically of drawable folder in array. currently i m using this code:

for(int i=1;i<=9;i++)
    {
            int imageKey = getResources().getIdentifier("img"+i, "drawable", getPackageName());
            ImageView image = new ImageView(this);  
            image.setId(imgId);
            image.setImageResource(imageKey);    
            image.setScaleType(ImageView.ScaleType.FIT_XY);
            viewFlipper.addView(image, new LayoutParams(LayoutParams.FILL_PARENT,              LayoutParams.FILL_PARENT));
            imgId++;
        }

but in that code i need to manually edit the image name to get the resource id but i want to get all image with any name..

2 Answers 2

20

you can Use Reflection to achieve this.

import the Field class

import java.lang.reflect.Field;

and then write this in your code

Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = new int[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
    try {
        resArray[i] = ID_Fields[i].getInt(null);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

resArray[] now holds references to all the drawables in your application.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you very much bro... its working now correctly but it also fetches the icon of application .. is dat any work around for it?
it simply gets all the drawable Ids which includes the icon. You are going to have to find out a way to exclude it in your logic(iterator/loop).
just exclude them when you traverse through the list
and with getName() you can get All resources property name. Thanks
8

Well, If your image names are img1, img2 and so on, then you can create a variable like

String url = "drawable/"+"img"+i;

int imageKey = getResources().getIdentifier(url, "drawable", getPackageName());

you can also replace your getPackageName() method by your package name like "com.android.resource"
Simply,the general function is

public int getIdentifier(String name, String defType, String defPackage)

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.