Right now, I\'m storing every XML layout file inside the \'res/layout\' folder, so it is feasible and simple to manage small projects, but when there is a case of large and
The top answer by @eski is good, but the code is not elegant to use, so I wrote a groovy script in gradle for general use. It's applied to all build type and product flavor and not only can be use for layout, you can also add subfolder for any other resources type such as drawable. Here is the code(put it in android
block of project-level gradle file):
sourceSets.each {
def rootResDir = it.res.srcDirs[0]
def getSubDirs = { dirName ->
def layoutsDir = new File(rootResDir, dirName)
def subLayoutDirs = []
if (layoutsDir.exists()) {
layoutsDir.eachDir {
subLayoutDirs.add it
}
}
return subLayoutDirs
}
def resDirs = [
"anims",
"colors",
"drawables",
"drawables-hdpi",
"drawables-mdpi",
"drawables-xhdpi",
"drawables-xxhdpi",
"layouts",
"valuess",
]
def srcDirs = resDirs.collect {
getSubDirs(it)
}
it.res.srcDirs = [srcDirs, rootResDir]
}
How to do in practice?
For example, I want to create subfolder named activity
for layout
, add a string by any name in resDirs
variable such as layouts
, then the layout xml file should be put in res\layouts\activity\layout\xxx.xml
.
If I want to create subfolder named selectors
for drawable
, add a string by any name in resDirs
variable such as drawables
, then the drawable xml file should be put in res\drawables\selectors\drawable\xxx.xml
.
The folder name such as layouts
and drawables
is defined in resDirs
variable, it can be any string.
All subfolder created by you such as activity
or selectors
are regarded as the same as res
folder. So in selectors
folder, we must create drawable
folder additionally and put xml files in drawable
folder, after that gradle can recognize the xml files as drawable normally.