Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

android - dynamically getting all image resource id in an array

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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...