【问题标题】:Warning: This <FrameLayout> can be replaced with a <merge> tag警告:此 <FrameLayout> 可以用 <merge> 标记替换
【发布时间】:2014-02-24 14:49:06
【问题描述】:

我有一个FrameLayout,其中包含一个TextView 和两个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 &lt;FrameLayout&gt; can be replaced with a &lt;merge&gt; tag.

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

【问题讨论】:

  • 附注:Generally, FrameLayout should be used to hold a single child view(来自文档)

标签: android xml android-framelayout android-lint


【解决方案1】:

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

例如,假设您有一个活动,这是您使用的布局 xml。这是放置布局文件之前 Activity 的布局。

<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 替换为 &lt;merge&gt; 标记。这就是它的样子。

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

注意没有额外的 FrameLayout。相反,它只是与活动的 FrameLayout 合并。只要有可能,您应该使用&lt;merge&gt;。这不仅适用于 FrameLayouts。你可以在这里读更多关于它的内容。 http://developer.android.com/training/improving-layouts/reusing-layouts.html#Merge

希望这会有所帮助。

【讨论】:

  • 如果布局需要通过 id 访问,你可能仍然需要一个 Fragment 标签,例如当它需要用作 Fragments 的容器时。
【解决方案2】:

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

<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 标签的子元素,并直接将它们插入到FrameLayout@android:id/content。使用HierarachyViewer 检查这两种方法(FrameLayoutmerge)以查看差异。

【讨论】:

  • chiuki,你能解释一下@android:id/content是什么吗? +1 建议 Hierarchy Viewer!
  • @android:id/content 是根 FrameLayout 的 ID,setContentView 放置您的布局。
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

    衡量:在这个阶段,父母和他们的孩子的大小和 他们的孩子,等等,都是衡量的。所以你的 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 标签实现。

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多