2010-11-09 70 views
40

我在我的xml(例如Button)中重複了很多控制。是否有可能在xml中寫入Button一次,然後將其導入我需要的所有佈局中?將xml導入另一個xml

+0

我面對這個問題時,我是打算做出像iOS導航欄的頂級欄。 – 2016-10-05 08:49:48

回答

93

您可以使用

<include layout="@layout/commonlayout" android:id="@+id/id" /> 

commonlayout.xmlres/layout定義,您可以添加重複的部分。

+0

工程。非常感謝 – Blackbelt 2011-02-02 14:36:30

+0

簡短但很好的答案。 – 2016-10-05 08:47:58

19

As Labeeb P正確地說,它的工作原理。 只是想補充一點,你也可以覆蓋參數太多:

<include 
     layout="@layout/commonlayout" 
     android:id="@+id/id" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:layout_marginLeft="2sp" 
     android:layout_marginRight="2sp" 
/> 
2

除了這些偉大的答案,你也可避免代碼重複使用<merge>標籤,就像這樣:

<merge xmlns:android="http://schemas.android.com/apk/res/android"> 

    <Button 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/add"/> 

    <Button 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/delete"/> 

</merge> 

<merge>當您將其包含到其他xml中時,它會被剝離。這可能有助於一次包括多個單獨的Button。請參閱official documentation

0

您可以使用默認include XML標籤包含一個外部佈局:

<include layout="@layout/somelayout" /> 

這種佈局應該有一個外ViewGroup封裝的內容或merge標籤,以避免使用不必要的佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:text="@string/hello_world" /> 

</LinearLayout> 

<!-- OR --> 

<merge xmlns:android="http://schemas.android.com/apk/res/android"> 

    <TextView android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:text="@string/hello_world" /> 

</merge> 

另外,如果你需要一個更好的辦法,包括佈局就像一個容器(自定義ViewGroup)的作品,你可以使用這個custom ViewGroup。請注意,這不會將XML導入另一個XML文件,它將從外部佈局中擴充內容並將其替換到視圖中。它類似於ViewStub,就像一個「ViewGroupStub」。

此lib中充當如果ViewStub可以用作以下(!注意這個例子不工作ViewStub不是ViewGroup!):

<ViewStub layout="@layout/somecontainerlayout" 
    inflate_inside="@+id/somecontainerid"> 

    <TextView android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:text="@string/hello_world" /> 

</ViewStub>