关于布局别名的 Android 文档不正确?

2023-12-22

我想弄清楚如何使用最少的样板代码重用或“别名”布局。

看来关于布局别名的 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>

第一种技术有效,你只需要把你的<resources>文件放在正确的文件夹中。它应该在values文件夹不是layout文件夹,就像您在重用布局时一样<include>.

例如,假设您有一个名为editor.xml生活在layout文件夹。假设您想使用专门的布局small and normal屏幕尺寸。如果您不介意重复,您只需将此布局复制并粘贴到layout-small and layout-normal文件夹并为其命名editor.xml在每个文件夹中。所以你会有三个名为editor.xml.

如果你不想重复,你可以将专门的布局放在主布局中layout文件夹并为其命名,例如compact_editor.xml。然后你会创建一个名为layout.xml in the values-small and values-normal文件夹。每个文件将读取:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="editor" type="layout">@layout/compact_editor</item>
</resources>

我已经提交了一份文件问题 http://code.google.com/p/android/issues/detail?id=38308关于另外两个问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于布局别名的 Android 文档不正确? 的相关文章

随机推荐