开发者

Android - how can I dynamically load drawables (pictures)? Names not known until run-time

I've searched Google and this website many times, but can not find a solution to my question.

First, I understand, you can load images using something like:

int image = R.drawable.icon; (assuming there's a file called 'icon.png')

and I've read about, and tried using:

getResources().getIdentifier("resname", "restype", com.example.whate开发者_如何学运维ver);

But, here's what I'm unable to do: I want to be able to have pictures in the /res/drawable folder (I believe that's the correct folder), WITHOUT KNOWING ANY OF THE NAMES OF THE FILES, and load them dynamically - at run-time.

One (of the many) things I've tried is (something like):

int[] images = new int[numberOfImages];
for( 0 to numberOfImages )
{
    images[i] = 
        getResources().getIdentifier("resname", "restype", com.example.whatever);
}

This returns 0 EVERY TIME, so it's not going to work

I'd like to get the name and integer identifier for every picture in the /res/drawables folder. Can this be done WITHOUT KNOWING ANY FILE NAMES?

----------------------------------------------------------------------

[adding this after the question was resolved to help anyone that may run into the same issue in the future. It just shows that it does in fact work.]

    Class resources = R.drawable.class;
    Field[] fields = resources.getFields();
    String[] imageName = new String[fields.length];     
    int index = 0;
    for( Field field : fields )
    {
        imageName[index] = field.getName();
        index++;
    }

    int result = 
            getResources().getIdentifier(imageName[10], "drawable", "com.example.name");


Well, if you have to do it, use reflection :)

Class resources = R.drawable.class;
Field[] fields = resources.getFields();
for (Field field : fields) {
    System.out.println(field.getName());
}

However, in a way, you are still hard-coding stuff, since you will only be putting a fixed set of drawables in your app. :)


As you stated in the comments, if you want to add files to that folder after the app is installed you'll have to use a private folder. Data storage documentation.

Then use a service to download images and add them to the private folder.

If you want the user to download the app with some preloaded images and you don't want to wait for the service run for the time to download the initial set of images, you can always send some images in the /res/raw folder and in the first time your app runs, copy these to your private folder.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜