Can the Android drawable directory contain subdirectories?

159,841

Solution 1

No, the resources mechanism doesn't support subfolders in the drawable directory, so yes - you need to keep that hierarchy flat.

The directory layout you showed would result in none of the images being available.

From my own experiments it seems that having a subfolder with any items in it, within the res/drawable folder, will cause the resource compiler to fail -- preventing the R.java file from being generated correctly.

Solution 2

The workaround I'm using (and the one Android itself seems to favor) is to essentially substitute an underscore for a forward slash, so your structure would look something like this:

sandwich_tunaOnRye.png
sandwich_hamAndSwiss.png
drink_coldOne.png
drink_hotTea.png

The approach requires you to be meticulous in your naming and doesn't make it much easier to wrangle the files themselves (if you decided that drinks and sandwiches should really all be "food", you'd have to do a mass rename rather than simply moving them to the directory); but your programming logic's complexity doesn't suffer too badly compared to the folder structure equivalent.

This situation sucks indeed. Android is a mixed bag of wonderful and terrible design decisions. We can only hope for the latter portion to get weeded out with all due haste :)

Solution 3

Actually, on Android Studio it is possible. You can have nested resources as shown here :

enter image description here

There is also a plugin to group resources here.

I recommend to avoid this though.

Solution 4

Yes - it does suck :) However you can use the assets folder and have sub directories in there and load images that way.

Solution 5

Use assets folder.

sample code:

InputStream is = null;
try {
    is = this.getResources().getAssets().open("test/sample.png");
} catch (IOException e) {
    ;
}

image = BitmapFactory.decodeStream(is);
Share:
159,841
Jay Wehrman
Author by

Jay Wehrman

I'm a Senior Software Engineer working on Calendar at Google. I'm interested in sharing my knowledge of software development and automation.

Updated on July 08, 2022

Comments

  • Jay Wehrman
    Jay Wehrman almost 2 years

    In the Android SDK documentation, all of the examples used with the @drawable/my_image xml syntax directly address images that are stored in the res/drawable directory in my project.

    I am wondering if it is explicitly not okay to create a sub directory within the drawable directory.

    For example, if I had the following directory layout:

    res/drawable
    -- sandwiches
      -- tunaOnRye.png
      -- hamAndSwiss.png
    -- drinks
      -- coldOne.png
      -- hotTea.png
    

    Could I reference the image of a tuna salad sandwich as @drawable/sandwiches/tunaOnRye

    Or do I have to keep the hierarchy flat in the drawable directory.