0

I have a folder structure inside my various drawable folders, e.g. drawable, drawable-hdpi etc.

Something like:

drawable-hdpi
├── folder_main
│   ├── sub_folder_1
│   │   ├── 1.png
│   │   └── 2.png
│   ├── sub_folder_2
│   │   ├── 1.png
│   │   └── 2.png
│   └── sub_folder_3
│       ├── 1.png
│       └── 2.png
└── ic_launcher.png

Accessing these resources will be dynamic and done programatically. I need a way to access these sub folder png resources.

Accessing the ic_launcher is straight forward using: R.drawable.ic_launcher. Logically I think you should be able to access the resource somthing like:

R.drawable.folder_main.sub_folder_1.1

But that clearly doesn't work and wouldn't work programatically where the sub folder and file is dynamic.

Thanks in advance for any pointers.

Bitswazsky
  • 4,242
  • 3
  • 29
  • 58
HGPB
  • 4,346
  • 8
  • 50
  • 86

3 Answers3

2

You can't create subfolders in resources folders. The hierarchy must remain flat. I don't think it would even compile.

znat
  • 13,144
  • 17
  • 71
  • 106
  • Yep, unfortunately true. It's something that devs have been requesting for a long time, but at this point is not possible. – Kevin Coppock Aug 20 '12 at 16:32
  • @kcoppock If i was to approach this using underscores as suggested in above link how can I dynamically get the image I want using the R.drawable approach. E.g. R.drawable.sub_folder_1_1 - Folder_1 being dynamic and 1 being the dynamically obtained png? – HGPB Aug 20 '12 at 16:37
  • I would highly advise against it, as it's much slower, but you can use getResources().getIdentifier() to parse a string into its corresponding resource id, see here: http://stackoverflow.com/a/10170925/321697 – Kevin Coppock Aug 20 '12 at 16:47
0

No, Android does not allow nested hierarchy structure in the resource folders. You would immediately get compilation errors if you tried something like that. Unfortunately, no sub-folders can be created inside the resource folders.

Swayam
  • 16,294
  • 14
  • 64
  • 102
0

Shortly after posting my question I found this stack overflow resource:

http://www.stackoverflow.com/a/10170925/321697

This, and the answers here solved my first problem to do with folder/file structure.

Then I needed a way to process these resources. I did this as follows:

I updated the file structure to:

drawable-hdpi
    ->name_1_0.png
    ->name_1_1.png
    ->name_1_2.png
    ->name_2_0.png
etc

I then accessed the files with the following code:

int folder = 1;
int image = 0;
int resourceIdentifier = resources.getIdentifier("name_"+folder+"_"+image,"drawable","*whateveryourpackageiscalled");

Note: *whateveryourpackageiscalled = com.yourwebsite.etc

This way I get to dynamically access the image I need by altering the folder and image variables.

HGPB
  • 4,346
  • 8
  • 50
  • 86