我有一个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.
为什么存在此警告?我该如何解决(除了忽略)?
要了解这一点,您需要了解布局是如何膨胀和放置的。
例如,您有一个活动,这是您使用的布局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希望这会有所帮助。
<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
检查这两种方法(merge
与HierarachyViewer
),以查看区别。