Taming android layout resources

Finding your way through the clutter

Right now, you are probably storing every xml layout file inside the layout/ folder. It is feasible and simple to manage in small projects, but when there is a case of large and heavy projects, things can get messy and specific files are now really hard to find.

So, is there any way to solve this problem?

Subfolder resource merging

The trick is to use gradle’s ability to merge multiple resource folders and set the res/ folder as well as the nested subfolders in the sourceSets block.

The quirk is that you can’t declare a container resource folder before you declare that folder’s child resource folders.

Below is the sourceSets block from the build.gradle file. Notice that the subfolders are declared first.

android {
sourceSets {
main {
res.srcDirs = [
'src/main/res/layout/signup',
'src/main/res/layout/profile',
'src/main/res/layout',
'src/main/res'
]
}
}
}

Now you can have this:

res/
layout/
signup/
layout/
register.xml
login.xml
forgot_password.xml
profile/
layout/
main.xml
notifications.xml

Awesome right? ☺

[update] Thanks to dmytrodanylyk for reminding me to add a subfolder called layout/ so it works properly!

Prepending categories to resources

I think the most elegant solution to this problem is to prepend the file names with the name of the folder you would have placed it inside of. For example, if you have a bunch of layouts for an Activity, Fragment, or just general view called “places” then you should just prepend it with places_my_layout_name. At least this solves the problem of organizing them in a way that they are easier to find within the IDE.

res/
layout/
signup_register.xml
signup_login.xml
signup_forgot_password.xml
profile_main.xml
profile_notifications.xml

Extending the prepended categories option

Android File Grouping Plugin

This open source plugin is very helpful in transforming the categories into fake directories and display your files as a group of different folders in the project structure view.


Hit me up on @cesarmcferreira if you have any questions☺