Layout design in Android Studio
Today when start optimizing the codebase of my project, I saw this:
For example, in a chat program you usually have 3 categories “home”, “profile” and “chat” corresponding to vertical groups of features.
Look at the list of XML files inside my
res/layout
folder. Horrible, right?
Now, look at yours. Is your
res/layout
too big, hard to control? Your project have too many features, too many screens? Let imagine while confusing running for the deadline, and you can’t find the XML layout that need to be fixed just because you can’t remember the file name.
Wandering search online, I find out that many people have the same problem as me. So I decide to write an article to share some tips for better manage
res/layout
folder in Android Studio.Step 1
First create a parent layouts folder. Right click in
res
, select New → Directory, type layouts
(remember the ‘s’ or it will be duplicated).
I call it “layouts” because it is parent folder to hold all layouts of our project.
Step 2
Select
layouts
, right click and select New → Folder → Res Folder. This resource folder will represent a “category” that you want.For example, in a chat program you usually have 3 categories “home”, “profile” and “chat” corresponding to vertical groups of features.
First, I will add
chat
as new Res Folder. When you’ve just added, wait a while for Gradle syncing to re-structure the program. After that, you will then see a yellow chat
folder in the res
but not inside the layouts
. Actually it’s still in layouts
, however, because we’ve just added only one folder chat
so it only shows chat
. Continue to create two more Res Folder for home
and profile
. After that, the project tree will appear exactly as what you expect: chat
, home
and profile
are now inside layouts
.
At this point, you’ve successfully divided the
layouts
into 3 separate categories.Step 3
Add a
layout
folder (without ‘s’) to each sub-folder corresponding to each category — like the traditional res/layout
. You can also add other type of resources: menu
, drawable
, anim
,..Step 4
Try re-sync Gradle and rebuild the project, you will see the following code was added inside the
android
tag of app/build.gradle
file.sourceSets { | |
main { | |
res.srcDirs = ['src/main/res', | |
'src/main/res/layouts/chat', | |
'src/main/res/layouts/home', | |
'src/main/res/layouts/profile' | |
] | |
} | |
}
This code corresponds to adding 3 categories: 3 resource folder chat , home and profile . If it’s not exist, you can add it manually.
|
Comments
Post a Comment