警告:此 <FrameLayout> 可以用 <merge> 标签替换。

22

我有一个包含TextView和两个LinearLayoutFrameLayout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    ... a textview and 2 linearlayouts


</FrameLayout>

运行 Android Lint 后,我收到了以下警告:This <FrameLayout> can be replaced with a <merge> tag.

这个警告是什么意思?除了忽略之外,我还能做些什么来解决它?


2
作为一个附注:“通常,FrameLayout 应该用于容纳单个子视图”(来自文档) - FD_
4个回答

32

要理解这一点,您需要了解布局是如何被填充和放置的。

例如,假设您有一个活动,这是您使用的布局XML。在您放置布局文件之前,该活动的布局如下所示:

<FrameLayout> // This is the window
    <FrameLayout> // This is activity
    </FrameLayout>
</FrameLayout>

根据设备/操作系统的不同,可能还会有其他的图层。

现在,当您填充布局文件并将其放置时,它将呈现为以下方式。

<FrameLayout> // This is the window
    <FrameLayout> // This is activity
            //A textview and 2 linearlayouts
    </FrameLayout>
</FrameLayout>

你是否看到另一个FrameLayout中的FrameLayout?由于它并没有增加太多价值,所以有点冗余。为了优化,你可以用<merge>标签替换外部FrameLayout。这就是它的样子。

<merge> // This is the window
    <FrameLayout> // This is activity
            //A textview and 2 linearlayouts
    </FrameLayout>
</merge>
注意观察一下,这里没有额外的FrameLayout。相反,它只是与活动的FrameLayout合并在一起。只要可以,就应该使用<merge>。这不仅适用于FrameLayouts。您可以在此处阅读更多信息。http://developer.android.com/training/improving-layouts/reusing-layouts.html#Merge 希望这有所帮助。

如果需要通过 id 访问布局(例如作为 Fragment 的容器),则仍然需要使用 Fragment 标签。 - user1841702

11

你是否将此作为活动的主要布局?如果是,则可以使用以下合并标记替换它:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    ... a textview and 2 linearlayouts


</merge>

setContentView 中,Android 将会获取 merge 标签的所有子标签,并将它们直接插入带有 @android:id/contentFrameLayout 中。使用 HierarachyViewer 检查两种方法(FrameLayout vs merge)的区别。


chiuki,你能解释一下@android:id/content是什么吗?感谢推荐Hierarchy Viewer - Alexander Suraphel
@android:id/content是根FrameLayout的ID,setContentView会将您的布局放置在这里。 - chiuki

1

请参考Romain Guy的this文章以获取更多信息。该文章会告诉您为什么建议使用合并选项。


0

为了在设备中呈现XML,需要按阶段进行处理,第一阶段是测量

测量:在此阶段,测量父级及其子级、子级的大小等。因此,您的CPU扫描布局中的所有ViewGroup和View以测量它们的大小。有时由于父级及其子级之间大小的依赖关系,可能需要递归地进行此扫描。

那么为什么Lint会发出此警告?

因为您的XML最终将加载到包含FrameLayout的窗口中,并且在您的XML文件中也使用了FrameLayout,因此最终您的XML将放置在窗口的FrameLayout中,就像这样:

<FrameLayout> <!--belongs to window-->
    <FrameLayout> <!--belongs to your XML-->
            ...
    </FrameLayout>
</FrameLayout>

现在在测量阶段,对于CPU来说存在一个开销,需要同时测量FrameLayout。如果我们能够以某种方式管理XML中的外部FrameLayout,那么这个开销就可以被克服,而这正是通过merge标签实现的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接