You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 > Files tab
  • 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.xml item from the group's file list
  • In the File Name Template field (right side of the window), replace the default filename with this path:
    res/layout/${NAME}_fragment.xml
    
    The ${NAME} variable pulls the base name you enter when creating the component (e.g., if you type Home, it generates res/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.kt and ProfileViewModel.kt will be in your target package
    • Profile_fragment.xml will now be generated directly in res/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:47:40