Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

android - Can some clarify usage of <include> and <merge>

I just need someone to tell me if I understood correctly when to use <include> and when <merge>.

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>

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>

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>

Have I understood this correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From my understanding it will set the merge element as the higher element in the view hierarchy. Include will simply put the whole viewgroup in there. So using your example the view hierarchy should look like:

With merge:

LinearLayout (root)
|
TextView

With include:

LinearLayout (root)
|
LinearLayout
|
TextView

So you will have an extra LinearLayout in the view hierarchy that you do not need. However, sometimes you need that intermediate view. In your case, you wouldn't, since both the LinearLayouts have the same layout params and no other differences.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...