I'd like to figure out how to reuse or "alias" layouts with the least boilerplate code.
It seems that the Android documentation about layout aliases is incorrect, and certainly appears inconsistent. This section of documentation shows the following layout file as an example:
<resources>
<item name="main" type="layout">@layout/main_twopanes</item>
</resources>
If I try to compile this, I get an Attribute is missing the Android namespace prefix
error. Even after adding the namespace to the resources
element, I get error: Error: String types not allowed (at 'type' with value 'layout').
Elsewhere in the Android documentation, they show a different and seemingly inverted and incorrect way to alias layouts:
To create an alias to an existing layout, use the element, wrapped in a
<merge>
. For example:<?xml version="1.0" encoding="utf-8"?> <merge> <include layout="@layout/main_ltr"/> </merge>
Running this results in the following error in LogCat E/AndroidRuntime(1558): android.view.InflateException: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true
. So this error seems to reinforce the fact that this <include>
<merge>
pair must be a mistake, because it requires an unnecessary parent View
.
Lastly there's the <merge>
documentation, which seems to contradict the former direction, making no mention of the inverted form of a top-level <merge><include/></merge>
.
To avoid including such a redundant view group, you can instead use the element as the root view for the re-usable layout. For example:
<merge xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/add"/> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/delete"/> </merge>
The first technique works, you just have to put your <resources>
file in the correct folder. It should be in the values
folders not the layout
folders as you might when reusing layouts via <include>
.
For instance, suppose you have a layout named editor.xml
that lives in the layout
folder. Suppose you want to use a specialized layout on small
and normal
screen sizes. If you didn't care about repeating yourself, you would just copy and paste this layout into the layout-small
and layout-normal
folders and name it editor.xml
in each folder. So you'd have three files named editor.xml
.
If you don't want to repeat yourself, you would place the specialized layout in the main layout
folder and name it, say, compact_editor.xml
. Then you'd create a file named layout.xml
in the values-small
and values-normal
folders. Each file would read:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="editor" type="layout">@layout/compact_editor</item>
</resources>
I've filed a documentation issue about the other two problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With