android-layoutandroid-studiocode-templates

Add linebreaks to XML layout template


Is it possible to modify the XML layout template in Android Studio so that the namespace and attributes appear on separate lines?

Generated by default template:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>

Preferred:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>

The default template (below) shows each attribute (not including the namespace) on separate lines, but these line breaks don't translate to the generated resource file.

Default layout resource template


Solution

  • The problem is that Android Studio isn't respecting line breaks in the XML templates.

    Solution

    1. Enable Keep line breaks in

      Settings > Editor > Code Style > XML > Other (tab)

    2. Add a line break before the namespace in the relevant (see Notes) code template(s) in

      Settings > Editor > File and Code Templates > Other (tab)

    Result

    XML layouts will now generate the namespace and attributes on separate lines, like so:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
    </LinearLayout>
    

    Notes