564

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.

9
  • 19
    Please note that capital letters are not allowed in the res directory.
    – Tyler
    Commented Jan 11, 2012 at 1:34
  • 1
    You can only do this with Gradle: stackoverflow.com/a/19859379 Commented Apr 7, 2014 at 8:13
  • 2
    Is it possible to have SIBLING directories to drawable, with the drawable functionality? So, res/tanks/drawble-[hdpi .. etc] and so on?
    – Fattie
    Commented May 23, 2014 at 8:45
  • 3
    It's 2021. Has this been solved yet?
    – Leszek
    Commented May 30, 2021 at 21:32
  • 4
    It's 2022. Has this been solved yet? Commented Apr 29, 2022 at 16:59

23 Answers 23

595

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.

15
  • 155
    As of Android 2.2, this doesn't cause a compiler error, but any subdirectories are ignored when generating the R class. This really sucks, and makes it hard to manage larger projects. =/
    – Nik Reiman
    Commented Jul 28, 2010 at 8:42
  • 79
    Totally agree. They need to come up with a better solution supporting sub-folders. It can't be that hard.
    – znq
    Commented Sep 6, 2010 at 17:22
  • 16
    Hopefully this will be resolved soon, i've got over 100 assets, and even then i coded some of them out. Total night mare trying to manage any marginally complex project.
    – Emile
    Commented Jan 6, 2011 at 16:40
  • 16
    This is the corresponding Issue in the Android issue tracker: code.google.com/p/android/issues/detail?id=2018
    – espinchi
    Commented Jul 20, 2011 at 17:55
  • 16
    100 assets... Try it with 16 thousand assets.
    – Mytheral
    Commented Jul 23, 2012 at 18:22
166

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 :)

3
  • 33
    Just a note that capital letters aren't allowed in the drawable folder. I get the error: "Invalid file name: must contain only [a-z0-9_.]" Commented Oct 12, 2013 at 2:34
  • 6
    +1 for "mixed bag of wonderful and terrible design decisions" Commented Apr 15, 2014 at 2:27
  • 1
    Hardly a workaround : rather "what you should do so as not to go completely mad". It's ludicrous to be limited to one directory.
    – RichieHH
    Commented Jul 19, 2014 at 15:26
45

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.

9
  • Hi, @android developer! I've tried to add this into build.gradle file: sourceSets { main { res { srcDir 'src/main/res/drawable/ic-toggle' } } }, but I've got "Uri is not registered" for xmlns:android="schemas.android.com/apk/res/android. What could be the case?
    – AlexKost
    Commented Dec 12, 2015 at 9:01
  • @AlexKost I actually tried this only once. I'm not experienced with it enough to help. Sorry. Commented Dec 12, 2015 at 10:03
  • 1
    @JoshHansen It's messy. Commented Mar 1, 2018 at 23:51
  • 1
    If any of the two files from different folders have same name, you may get an error.
    – arjun
    Commented Apr 16, 2018 at 5:25
  • 2
    @BenjaminMesing While I know this solution exists, I'm against using it because it seems like a big workaround. Commented Sep 22, 2020 at 6:27
38

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

3
  • 11
    the problem is not only for drawable folder but also for layout folder :( My layout's folder contains more than 100 xml files, and it's hard for me to open the right xml layout in this.
    – anticafe
    Commented Jan 12, 2011 at 16:32
  • Appart for other objections, resources may be easily localized but AFAIK there is no l10n in-built mechanism for assets. Commented Jul 5, 2012 at 11:02
  • @anticafe use "Go to resource" in your IDE (Eclipse: CTRL+SHIFT+R, IDEA/Android Studio: CTRL+SHIFT+N)
    – TWiStErRob
    Commented Oct 19, 2014 at 22:23
24

Use assets folder.

sample code:

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

image = BitmapFactory.decodeStream(is);
3
  • 5
    The only issue with this method is that there is a LOT more homework involved with using bitmaps. Android's resource system does a much better job of memory management. Why would you rebuild a memory management system when Android already does it? Espeically if he has 100+ images, that's a lot of loading and releasing of bitmaps.
    – Rev Tyler
    Commented Jun 30, 2012 at 20:13
  • 23
    This is a real problem is you plan to localize your application, also if you have different resources for different screen densities, so it is not a solution, just a workaround valid for only some cases. Commented Jul 5, 2012 at 11:14
  • 1
    I need to give @Fran 's comment at least a thousand upvotes :)
    – HGPB
    Commented Aug 20, 2012 at 16:30
22

I've wrote an eclipse plugin which allows to create virtual subfolder by separating the file name with two underscores __. The project is in early stages, but don't worry it won't crash your IDE

more details can be found here, feel free to fork and send pull requests:

https://github.com/kirill578/Android-Sorted-Res-Folder

enter image description here

2
  • 2
    Nice! Any chance of porting this to Android Studio as well?
    – BVB
    Commented May 5, 2014 at 20:12
  • 1
    I'm currently not even using android studio, so I guess, we will have to wait for some experienced to port it. Commented May 5, 2014 at 20:15
9

I like to use a simple script to flatten an organized directory structure provided by designers to something that can be used to generate an R file.

Run with current path in drawable-hdpi:

#! /bin/bash
DIRS=`find * -type d`
for dir in ${DIRS} ; do 
  for file in `ls ${dir}` ; do
    mv ${dir}/${file}  ${dir}_${file};
  done 
  rmdir ${dir};
done
1
  • 1
    Your script will not work if there is sub folders under folders. I think you need to replace all '/' with '_' in ${dir}.
    – Seunghoon
    Commented Jun 8, 2012 at 23:38
9

In android studio with gradle you can have multiple source directors which will allow you to separate resources. For example:

android {
    ....
    android.sourceSets {
        main.res.srcDirs = ['src/main/extraresdirnamed_sandwiches', 'src/main/res']
    }
    ....
}

However the names must not collide which means you will still need to have names such as sandwiches_tunaOnRye but you will be able to have a seperate section for all of your sandwiches.

This allows you to store your resources in different structures (useful for auto generated content such as actionbargenerator)

6

One way to partially get around the problem is to use the API Level suffix. I use res/layout-v1, res/layout-v2 etc to hold multiple sub projects in the same apk. This mechanism can be used for all resource types.

Obviously, this can only be used if you are targeting API levels above the res/layout-v? you are using.

Also, watch out for the bug in Android 1.5 and 1.6. See Andoroid documentation about the API Level suffix.

3
  • To whoever downgraded this answer: Can you explain why? This mechanism, although not pretty, works well for me.
    – OferR
    Commented Dec 14, 2012 at 11:48
  • This is what I do as well and it works good enough. I have a bunch of small images that I don't want to expand out, so I keep them in their own folder.
    – AaronC
    Commented Oct 12, 2021 at 23:27
  • Works well for me. And it is pretty for me. I am trying to add version 2 logic into my app. so v2 is good.
    – bronze man
    Commented Oct 11, 2023 at 7:50
6

There is a workaround for this situation: you can create a resVector (for example) folder on the same level as default res folder. There you can add any drawable-xxx resource folders there:

resVector
-drawable
-layout
-color

After that all you need is to add

sourceSets {
        main.res.srcDirs += 'src/main/resVector'
    }

into your build.gradle file (inside android { }).

3
  • 1
    Sadly they're merge together in the project panel in Android Studio when using the "Android" perspective :( Commented Jan 14, 2018 at 7:24
  • @AjahnCharles - I prefer not to use this perspective at all (anyway - I'm always working at 'distraction free mode')... But you are right - "Android" merges everything. Commented Apr 3, 2018 at 12:24
  • This solution works well. Better than res/drawable-v2 solution. Easy to copy all to another Module or project.
    – bronze man
    Commented Oct 11, 2023 at 7:58
3

With the advent of library system, creating a library per big set of assets could be a solution.

It is still problematic as one must avoid using the same names within all the assets but using a prefix scheme per library should help with that.

It's not as simple as being able to create folders but that helps keeping things sane...

1
  • Yes, I think this is good. If I add country flags to my drawable-ldpi etc. folders then they will get swamped. I think that creating a library project for all generic resources will help reduce the clutter in the project that you are actively working on. Surprised you only have 1 upvote.
    – Tom
    Commented Jul 22, 2013 at 22:48
1

This is not perfect methods. You have to implement same way which is display here.

You can also call the image under the folder through the code you can use

Resources res = getResources();
Drawable shape = res. getDrawable(R.drawable.gradient_box);

TextView tv = (TextView)findViewByID(R.id.textview);
tv.setBackground(shape);
1

Not mine but I found this thread when looking for this issue, if your using Android Studio and Gradle Build system its pretty easy no plugins necessary just a little build file editing

https://stackoverflow.com/a/22426467/618419

1

Gradle with Android Studio could do it this way (link).

It's in the paragraph "Configuring the Structure"

sourceSets {
 main {
    java {
        srcDir 'src/java'
    }
    resources {
        srcDir 'src/resources'
    }
 }
}
1

create a folder in main. like: 'res_notification_btn'

and create tree folder in. like 'drawable' or 'layout'

then in 'build.gradle' add this

sourceSets
            {
                main
                {
                    res
                    {
                        srcDirs = ['src/main/res_notification_btn', 'src/main/res']
                      or
                        srcDir 'src/main/res_notification_btn'
                    }
                }
            }
0
#!/usr/bin/env ruby

# current dir should be drawable-hdpi/ etc

# nuke all symlinks
Dir.foreach('.') {|f|
    File.delete(f) if File.symlink?(f)
}

# symlink all resources renaming with underscores
Dir.glob("**/*.png") {|f|
    system "ln -s #{f} #{f.gsub('/', '_')}" if f.include?("/")
}
1
  • All this does is automate the workaround suggested by Cheezmeister. It's working for me ... care to explain the downvote? Commented Jun 18, 2013 at 18:38
0

Check Bash Flatten Folder script that converts folder hierarchy to a single folder

0

assets/ You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data. http://developer.android.com/tools/projects/index.html

0
0

Subdirectories are not allowed, the resource must contain only [a-z0-9_.].

No you have uppercase letters, and no forward slashes.

0

It is possible to have multiple drawable folders by having an extra folder parallel to 'res' with a subdirectory 'drawable' and then add following to gradle:

sourceSets {
    main {
        res.srcDirs 'src/main/<extra_res>'
    }
}

Tested with gradle 6.5.1

0

For anyone using Xamarin (either Xamarin.Android or Xamarin.Forms), there is a way to do this.

In the .csproj file for the Android project find the line for MonoAndroidResourcePrefix (documented, though rather poorly, here). Add the subdirectories you are wanting to use here, separating each entry by semicolons. When building, Visual Studio strips these prefixes so that all of the resources end up in a flat hierarchy. You may need to reload the solution after making these changes.

Example of setup in Xamarin

These directories do not need to be subdirectories of the default Resources directory in the project.

Make sure that files you add are getting the build action set to "AndroidResource".

For Xamarin.Android, the visual editor won't recognize images and will show the error "This resource URL cannot be resolved" but the project will build and the image will be visible at runtime.

Error in editor Example in emulator

0

I wanted to organize all my drawables into categories. This cannot be achieved using the regular directory structure, so my solution was to build the following directory structure:

- res
    - drawable
- organised_res
    - category1
          - drawable
    - category2
          - drawable
    - ...
    - categoryn
          - drawable

And then let gradle know about all the new resource directories I added: In build.gradle.kts, under android element I added:

sourceSets.getByName("main") {
    res.srcDirs("src/main/organised_res/category1",
                "src/main/organised_res/category2",
                ...
                "src/main/organised_res/categoryn")
}

It's important to take into account that all drawable folders of all categories (and other resources) will be merged into a single non-hierarchical flat structure, so a pic.jpg in one of those dirs can be accessed from code simply as R.drawable.pic. Therefore it's important to make sure that all file names are unique.

-6
  1. Right click on Drawable
  2. Select New ---> Directory
  3. Enter the directory name. Eg: logo.png(the location will already show the drawable folder by default)
  4. Copy and paste the images directly into the drawable folder. While pasting you get an option to choose mdpi/xhdpi/xxhdpi etc for each of the images from a list. Select the appropriate option and enter the name of the image. Make sure to keep the same name as the directory name i.e logo.png
  5. Do the same for the remaining images. All of them will be placed under the logo.png main folder.

Not the answer you're looking for? Browse other questions tagged or ask your own question.