21

我有一个FrameLayout包含 aTextView和两个LinearLayouts:

<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.

为什么存在此警告?我能做些什么来修复它(除了忽略)?

4

4 回答 4

31

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

例如,假设您有一个活动,这是您使用的布局 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了吗?拥有它是多余的,因为它不会增加太多价值。要进行优化,您可以将外部FrameLayout 替换为<merge>标签。这就是它的样子。

<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

希望这可以帮助。

于 2014-01-31T21:51:54.440 回答
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 会获取合并标签的孩子,并直接将它们插入到FrameLayoutwith 中@android:id/content。检查这两种方法 ( FrameLayoutvs merge)HierarachyViewer以查看差异。

于 2014-01-31T21:53:16.120 回答
1

有关更多信息,请参阅Romain Guy 的这篇文章。它告诉您为什么建议使用合并选项。

于 2014-02-14T14:55:57.710 回答
0

为了在设备中呈现 XML,需要分阶段进行,第一个是Measure

测量:在这个阶段,测量父母和他们的孩子和他们的孩子的大小,等等。因此,您的 CPU 会扫描布局中的所有 ViewGroup 和 View 以测量它们的大小。有时由于某些原因,它可能需要递归扫描,因为父母和他们的孩子的大小相互依赖。

那么为什么 Lint 会给出这个警告呢?

因为您的 XML 最终将被加载到包含 FrameLayout 的窗口中,并且在您的 XML 文件中您也在使用 FrameLayout,所以最终您的 XML 将被放置在窗口的 F​​rameLayout 中,它将是这样的:

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

现在,在测量阶段 CPU 会产生开销,以测量FrameLayout. 如果我们能够以某种方式设法FrameLayout在 XML 中使用外部,则可以克服这种开销,这完全可以通过merge标记实现。

于 2020-10-11T11:50:43.440 回答