问题描述
我只需要有人告诉我是否正确理解了何时使用 <include>
以及何时使用 <merge>
.
I just need someone to tell me if I understood correctly when to use <include>
and when <merge>
.
所以,我制作了一个标题布局,我想将它包含到其他 XML 布局中:
So, I make a header layout which I want to include into some other XML layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header text" />
</LinearLayout>
我以这种方式将它包含到其他一些 XML 中(这是非常基本的):
And I include it into some other XML this way (which is pretty basic):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<include
android:id="@+id/header"
layout="@layout/top"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
这会很好用,没有问题.但是为了优化代码,我必须在包含的布局中使用 <merge>
.所以 top layout
不应该有标签 <LinearLayout>
但它必须看起来像这样:
This will work well, no issue about it. But in order to optimize the code, I have to use <merge>
in the layout which gets included. So the top layout
should not have a tag <LinearLayout>
but it must look like this:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header text" />
</merge>
我理解正确吗?
推荐答案
是的,你理解正确.merge
用作伪父元素以减少视图树中的级别数.只需检查这个 link,它对 link 给出了很好的解释代码>合并代码>.
Yes you understood it correctly. merge
is used as pseudo parent element to reduce the number of levels in view trees.
Just check this link, it gives very good explanation of merge
.
在你的头文件中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<include
android:id="@+id/header"
layout="@layout/top"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
当您的文件包含在您提到的其他文件中时,
<LinearLayout>
没有任何区别.所以用 merge
代替是件好事.
<LinearLayout>
doesn't make any difference when your file is included in other file you mentioned. So it's a good thing to use merge
instead.
由于在 XML 中必须使用单个父元素,并且其余的 XML 元素都应该包含在其中,所以应该使用 merge
作为单个父元素,并且可以避免添加不必要的父布局.
Since in XML you must use a single parent element and the rest of the XML elements should be included in it, you should use merge
as single parent element and can avoid adding unnecessary parent layout.
当您想要应用与包含您的内容的文件中定义的布局不同的布局时,请避免合并".
Just avoid 'merge' when you want to apply a layout differently than layout is defined in file in which your content is inclded.
这篇关于可以澄清一下<include>的用法吗?和<合并>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!