什么是Android的&LT的目的;合并>标签在XML的布局?目的、布局、标签、LT

2023-09-12 21:42:31 作者:蜜桃味奶罐

我读过罗曼盖伊的帖子上的 <合并/> 标记,但我还是不明白它是如何的有用。它是一个排序的更换&LT的;帧/> 标记,或者是使用像这样:

I've read Romain Guy's post on the <merge /> tag, but I still don't understand how it's useful. Is it a sort-of replacement of the <Frame /> tag, or is it used like so:

<merge xmlns:android="....">
<LinearLayout ...>
    .
    .
    .
</LinearLayout>
</merge>

然后&LT;有/&GT; 的code在另一个文件

then <include /> the code in another file?

推荐答案

&LT;合并/&GT; 是有用的,因为它可以摆脱不必要的ViewGroups,即布局,只是用来包裹其他意见,没有用他们自己。

<merge/> is useful because it can get rid of unneeded ViewGroups, i.e. layouts that are simply used to wrap other views and serve no purpose themselves.

例如,如果你要&LT;有/&GT; 从另一个文件布局,而不使用合并,这两个文件可能是这个样子:

For example, if you were to <include/> a layout from another file without using merge, the two files might look something like this:

layout1.xml:

layout1.xml:

<FrameLayout>
   <include layout="@layout/layout2"/>
</FrameLayout>

layout2.xml:

layout2.xml:

<FrameLayout>
   <TextView />
</FrameLayout>

这在功能上等同于该单布局:

which is functionally equivalent to this single layout:

<FrameLayout>
   <FrameLayout>
      <TextView />
   </FrameLayout>
</FrameLayout>

这的FrameLayout在layout2.xml可能没有用处。 &LT;合并/&GT; 帮助摆脱它。下面是它看起来像使用合并(layout1.xml不改变):

That FrameLayout in layout2.xml may not be useful. <merge/> helps get rid of it. Here's what it looks like using merge (layout1.xml doesn't change):

layout2.xml:

layout2.xml:

<merge>
   <TextView />
</merge>

这是功能上等同于该布局:

This is functionally equivalent to this layout:

<FrameLayout>
   <TextView />
</FrameLayout>

但由于您使用的是&LT;有/&GT; 你可以在其他地方重复使用的布局。它没有被用来取代只FrameLayouts - 你可以用它来替换不加入一些有用的东西到你的观点看起来/行为方式的任何布局

but since you are using <include/> you can reuse the layout elsewhere. It doesn't have to be used to replace only FrameLayouts - you can use it to replace any layout that isn't adding something useful to the way your view looks/behaves.