警告:此<FrameLayout>可以替换为<merge>标记

Ole*_*siy 17 xml android android-lint android-framelayout

我有一个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>
Run Code Online (Sandbox Code Playgroud)

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

为什么会出现此警告?我该怎么做才能解决它(除了忽略)?

Asw*_*ran 29

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

比方说,您有一个活动,这是您使用的布局xml.以下是在放置布局文件之前活动的布局.

<FrameLayout // This is the window
    ...
    <FrameLayout> // This is activity
    </FrameLayout>
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

根据设备/操作系统,可能还有一些其他层.

现在,当您为布局文件充气并将其放入时,这就是它的外观.

<FrameLayout // This is the window
    ...
    <FrameLayout> // This is activity
        // Your layout below
        <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>
    </FrameLayout>
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

你在FrameLayout中看到了FrameLayout吗?拥有它是多余的,因为它没有增加太多价值.要进行优化,可以使用<merge>替换FrameLayout.如果你使用,这就是它的样子.

<FrameLayout // This is the window
    ...
    <FrameLayout // This is activity
        // Your layout below
                ... a textview and 2 linearlayouts
    </FrameLayout>
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

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

希望这可以帮助.


chi*_*uki 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>
Run Code Online (Sandbox Code Playgroud)

setContentView,Android将采取合并标记的子项并直接将它们插入到FrameLayoutwith @android:id/content.检查两种方法(FrameLayoutvs merge)HierarachyViewer以查看差异.