Wednesday, February 13, 2013

Subdirectories in drawable folder - Android?


In Android SDK documentation, all of the examples shown used @drawable/someimage directly address images that are stored in res/drawable directory..

I wondered will it  be possible to create subfolders under drawable folder.. something like


res/drawable
-- fruits
  -- apple.png
  -- orange.png
-- vegetables
  -- cabbage.png
  -- carrot.png

Later I found that it is not possible to create subfolders under drawable directory.. we need to keep the hierarchy flat. Having subfolders under drawable directory will cause the compiler to fail - preventing R.java from being generated correctly..

So what is the workaround??

We can create subfolders under assets directory and load images from there.


Sample code to load images from Assets directory
InputStream is = null;
try {
    is = this.getResources().getAssets().open("fruits/apple.png");
} catch (IOException e) {
    //something
}

image = BitmapFactory.decodeStream(is);