Day054 — Organize res folder better
I want to have a better organization for the resources in my android project. Typically, all the layout xml files are stored in res/layout
. As the app grows bigger and bigger, the number of xml files live in the folder can be more than a dozen. To make it more manageable and readable, it is best to group related layout files inside a folder. Here is how it is done.
Original structure
-src
-main
-java
-res
-layout
-activity1_1.xml
-activity1_2.xml
-activity2.xml
Better organized structure
-src
-main
-java
-res
-layout
-activity1
-activity1_1.xml
-activity1_2.xml
-activity2.xml
How to
Below is the android project that the first activity create the second activity upon clicking on a button. The layout of the second activity is stored with its class instead of res/layout
.
The key is to add the path to the sourceSets
.
It happens in below commit.
The android project demonstrates how to do it for layout, but it applies to all resources folder, like drawable, string, and dimen, as long as you reference the folder correctly in the app’s build.gradle
. It works on both Java and Kotlin project, of course.
You can see the activity_another.xml
from the android project structure in Android Studio.
Tips
You would not know whether the path is correct or not. It will not prompt an error message telling you the path is wrong.
res.srcDirs += 'com/obviously_a_wrong_path/res'
To find the correct path, you can add manifest.srcFile ‘AndroidManifest2.xml’
to the main scope.
sourceSets {
main {
manifest.srcFile 'AndroidManifest2.xml'
srcDirs.forEach {
res.srcDirs += 'com/obviously_a_wrong_path/res'
}
}
}
Since there is no AndroidManifest2.xml
, an error message will occur.
Cannot read packageName from /Users/jackytsang/GithubRepos/CodingEveryday/Day054-Organize res folder better/OrganizeRes/app/AndroidManifest2.xml
Then you will know that the root file path is
/Users/jackytsang/GithubRepos/CodingEveryday/Day054-Organize res folder better/OrganizeRes/app/
Use this to deduce the path needed to go to the AnotherActivity
folder, which is
src/main/java/com/example/jackytsang/organizeres/
The final code would be
sourceSets {
main {
srcDirs.forEach {
res.srcDirs += 'src/main/java/com/example/jackytsang/organizeres/' + it + '/res'
}
}
}