Android Studio组文件模板中如何为XML子文件指定res/layout/目录路径
How to Direct Your XML Layout to res/layout/ in an Android Studio Group File Template
Alright, let's get your group file template sorted so that your fragment_layout.xml lands right in res/layout/ instead of cluttering up your Kotlin package directory. Here's exactly how to make this work:
Step 1: Open Your Group Template Settings
First, head to Android Studio's settings:
- On Windows/Linux: Go to
File > Settings - On macOS: Go to
Android Studio > Settings - Navigate to
Editor > File and Code Templates > Filestab - Locate your custom group template (if you haven't finished creating it, click the
+button under "Group templates" to start building it)
Step 2: Configure the XML File's Path
For the XML file entry in your group template:
- Select the
fragment_layout.xmlitem from the group's file list - In the File Name Template field (right side of the window), replace the default filename with this path:
Theres/layout/${NAME}_fragment.xml${NAME}variable pulls the base name you enter when creating the component (e.g., if you typeHome, it generatesres/layout/Home_fragment.xml). Feel free to tweak the suffix (_fragment) to match your team's naming convention.
Step 3: Double-Check Your Kotlin File Paths (Optional)
If you want to make sure your Kotlin files land in the right package directory, their File Name Templates should use the ${PACKAGE_NAME} variable, like:
- For the Fragment:
${PACKAGE_NAME}/${NAME}Fragment.kt - For the ViewModel:
${PACKAGE_NAME}/${NAME}ViewModel.kt
This keeps them in your selected package while sending the XML to the resource directory.
Step 4: Test the Template
Give it a spin to confirm:
- Right-click your module >
New > [Your Group Template Name] - Enter a base name (e.g.,
Profile) - Check your project structure:
ProfileFragment.ktandProfileViewModel.ktwill be in your target packageProfile_fragment.xmlwill now be generated directly inres/layout/
Quick Tips
- Android Studio will automatically create the
res/layout/directory if it doesn't exist, but it's better to have a standard Android project structure set up first. - If you need to use custom variables (like a specific subpackage for UI components), you can define them in the group template's "Variables" section, but
${NAME}and${PACKAGE_NAME}cover most common use cases.
That's all there is to it! This relative path trick in the File Name Template is the key to separating your Kotlin and resource files when using group templates.
内容的提问来源于stack exchange,提问作者Hussien Fahmy
相关产品推荐
相关产品推荐

