3

In Android Studio, can layout xml files be grouped into folders?

Able to do it with the java files by creating different packages/folders, can the layout files be similarly grouped/organized?

Looking for ease of organization in my workflow when i have a ton of xml files to work with.

user1406716
  • 9,565
  • 22
  • 96
  • 151

2 Answers2

4

No, the files have to be in predefined folders.

Here is a link to more information on available folder names: http://developer.android.com/guide/topics/resources/providing-resources.html

Daniel Gabriel
  • 3,939
  • 2
  • 26
  • 37
2

Actually, they can!

Although the steps are a bit too many, it is indeed possible to group your xml files in folders. Just follow the following steps:

  1. Switch to Project view; you can now see all your project folders and sub-folders properly.

  2. Backup all your layout files; at this stage you'll find them all under android/app/src/main/res/layout.

  3. Delete the entire layout directory (android/app/src/main/res/layout). Remember to properly backup all your layout files before this step.

  4. Right click the res directory and select "New" and then select "Directory".

  5. Give it a name; remember the name must be entirely lowercase. Your new directory will now appear under the res folder. Let's call this directory layouts for instance.

  6. Right click your new directory (layouts) and select "New" and then select "Directory". This way, we are creating a new sub-directory. We can give it any name we want, just remmber it must be completely lowercase.

  7. You can repeat step 6 as many times as you want and keep creating sub-directories.

  8. VERY IMPORTANT! Right click any of the sub-directories and select "New" and then select "Directory". YOU MUST NAME THIS DIRECTORY layout.

  9. Repeat this for all sub-directories.

  10. Move all the backed-up xml files (in step 2) to the layout directory of the folder you want to put them in.

  11. Add the code below to your build.gradle (app) file:

    sourceSets {

    main {
    
       res.srcDirs =
         [
           'src/main/res/layouts/layout_for_fragment',
           'src/main/res/layouts',
           'src/main/res'
         ]
        }
     }
    

Replace layouts with your sub-directory name and add as many sub-directories as are available.

  1. Sync project with gradle files

And that's it.. Pretty herculean but it can come in handy anytime. You may want to visit this link for more clarification.

I hope this helps.. Merry coding!

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
  • yes it works, but you forgot to mention `sourceSets ` should go inside `android` tags. I was looking around for like 15 mins coz I put it outside :). but project navigator still put all xmls under a same layout virtual group even thought those xmls are on different folders. is there a way to change that too? – RJE Jul 05 '18 at 03:06