问题
I have a FrameLayout
that contains a TextView
and two LinearLayout
s:
<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>
After running Android Lint, I get this warning: This <FrameLayout> can be replaced with a <merge> tag.
Why does this warning exist? What can I do to fix it (other than ignore)?
回答1:
To understand this, you need to understand how layout are inflated and placed.
Let's say for example, you have a activity and this is the layout xml you use. Here is what the layout of the activity looks before you put your layout file.
<FrameLayout // This is the window
...
<FrameLayout> // This is activity
</FrameLayout>
</FrameLayout>
There might be a few other layers depending on the device/OS.
Now when you inflate your layout file and put it in, this is how it will look.
<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>
Do you see the FrameLayout inside a FrameLayout? It is redundant to have that since it does not add much value. To optimize, you can replace your FrameLayout with a < merge >. If you use , this is what it will look like.
<FrameLayout // This is the window
...
<FrameLayout // This is activity
// Your layout below
... a textview and 2 linearlayouts
</FrameLayout>
</FrameLayout>
Notice how there is no extra FrameLayout. Instead, it is just merged with the FrameLayout of the activity. Whenever you can, you should use < merge >. This doesn't only apply to FrameLayouts. You can read more about it here. http://developer.android.com/training/improving-layouts/reusing-layouts.html#Merge
Hope this helps.
回答2:
Are you using this as the main layout of your activity? If so, you can replace it with a merge tag like this:
<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>
At setContentView
, Android will take the children of the merge tag and directly insert them to the FrameLayout
with @android:id/content
. Examine both approaches (FrameLayout
vs merge
) with HierarachyViewer
to see the difference.
回答3:
Refer this post by the Romain Guy for more information. It tells you why the merge option is suggested.
来源:https://stackoverflow.com/questions/21488027/warning-this-framelayout-can-be-replaced-with-a-merge-tag