现在,我在'res/layout'文件夹内存储每个XML布局文件,因此管理小型项目是可行和简单的,但当有大型和繁重的项目的情况下,那么应该有一个层次结构和子文件夹内需要的布局文件夹。
如。
layout
-- layout_personal
-- personal_detail.xml
-- personal_other.xml
--layout_address
-- address1.xml
-- address2.xml
同样,我们希望大型应用程序有子文件夹,那么在Android项目中有办法做到这一点吗?
我能够在布局文件夹内创建layout-personal和layout_address子文件夹,但当需要使用R.layout访问XML布局文件时。_______,当时在菜单中没有任何XML布局弹出。
我这样做的一种方式是在你的项目中创建一个与实际res文件夹相同级别的单独的res文件夹,然后你可以在你的应用程序build.gradle中使用这个
android {
//other stuff
sourceSets {
main.res.srcDirs = ['src/main/res', file('src/main/layouts').listFiles()]
}
}
然后每个新res文件夹的子文件夹可以一些有关每个特定屏幕或一些在你的应用程序,和每个文件夹都有自己的布局/可拉的价值观等保持事物的组织和你不必须手动更新gradle文件和其他一些答案要求(同步你gradle每次添加一个新的资源文件夹,所以它知道它,并确保添加相关的子文件夹之前添加xml文件)。
答案是否定的。
我想提请您注意这本书Pro Android 2,它指出:
It is also worth noting a few
constraints regarding resources.
First, Android supports only a linear
list of files within the predefined
folders under res. For example, it
does not support nested folders under
the layout folder (or the other
folders under res).
Second, there are some similarities
between the assets folder and the raw
folder under res. Both folders can
contain raw files, but the files
within raw are considered resources
and the files within assets are not.
Note that because the contents of the
assets folder are not considered
resources, you can put an arbitrary
hierarchy of folders and files within
it.
顶部答案有几个缺点:你必须添加新的布局路径,AS将新的资源放在res\layouts文件夹而不是res\values。
结合几个答案,我写下了类似的内容:
sourceSets {
main {
res.srcDirs =
[
'src/main/res',
file("src/main/res/layouts/").listFiles(),
'src/main/res/layouts'
]
}
}
我用这篇文章做了文件夹:http://alexzh.com/tutorials/how-to-store-layouts-in-different-folders-in-android-project/。为了创建子文件夹,你应该使用这个菜单:新建>文件夹> Res文件夹。
更新
几周后,我发现Android Studio并没有注意到资源的变化。于是,一些奇怪的虫子出现了。例如,布局仍然显示旧的尺寸和页边距。有时AS找不到新的xml文件(特别是在运行时)。有时它混合了视图id(对另一个xml文件的引用)。通常需要按Build > Clean Project或Build > Rebuild Project。在Android Studio中更改xml布局文件后,阅读需要重新构建的文件。