警告:此 可以替换为 标签

问题描述 投票:18回答:3

我有一个FrameLayout,其中包含一个TextView和两个LinearLayout

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

为什么存在此警告?我该如何解决(除了忽略)?

android xml android-framelayout android-lint
3个回答
30
投票

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

例如,您有一个活动,这是您使用的布局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?这样做是多余的,因为它不会增加太多价值。为了进行优化,可以将[[outer 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

希望这会有所帮助。


8
投票
您是否将其用作活动的主要布局?如果是这样,您可以将其替换为合并标记,如下所示:

<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将采用合并标记的子代,然后将其直接插入FrameLayout@android:id/content中。用FrameLayout检查这两种方法(mergeHierarachyViewer),以查看区别。

1
投票
请参阅Romain Guy的this帖子以了解更多信息。它告诉您为什么建议使用合并选项。
© www.soinside.com 2019 - 2024. All rights reserved.