我想弄清楚如何使用最少的样板代码重用或“别名”布局。
看来关于布局别名的 Android 文档 http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters是不正确的,而且肯定显得不一致。本部分文档以以下布局文件为例:
<resources>
<item name="main" type="layout">@layout/main_twopanes</item>
</resources>
如果我尝试编译它,我会得到一个Attribute is missing the Android namespace prefix
错误。即使将命名空间添加到resources
元素,我得到error: Error: String types not allowed (at 'type' with value 'layout').
Android 文档中的其他地方 http://developer.android.com/guide/topics/resources/providing-resources.html#AliasResources,它们显示了一种不同的、看似颠倒且不正确的别名布局方式:
要为现有布局创建别名,请使用该元素,
包裹在一个<merge>
。例如:
<?xml version="1.0" encoding="utf-8"?>
<merge>
<include layout="@layout/main_ltr"/>
</merge>
运行此命令会导致 LogCat 中出现以下错误E/AndroidRuntime(1558): android.view.InflateException: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true
。所以这个错误似乎强化了这样一个事实<include>
<merge>
配对一定是一个错误,因为它需要一个不必要的父母View
.
最后还有<merge>文档 http://developer.android.com/training/improving-layouts/reusing-layouts.html#Merge,这似乎与前一个方向相矛盾,没有提到顶级的倒置形式<merge><include/></merge>
.
为了避免包含这样的冗余视图组,您可以使用
该元素作为可重用布局的根视图。为了
例子:
<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>