2013-03-14 50 views
1

假設我有一個佈局文件,我想將其用作另一個佈局的一部分,我該怎麼做?將多個xml文件合併爲一個最終的android佈局

例如,我有一個表格佈局/res/layout/table.xml。我想在/res/layout/relative_stuff.xml的相對佈局中使用該表作爲組件。假設我的相對佈局是包含表格和兩個按鈕。

簡單的情況是完全在relative_stuff.xml文件中完成組合。但更好的情況是能夠以編程方式設置表xml:現實是我想從許多不同的表中選擇,現在說兩個表:/res/layout/table_1.xml/res/layout/table_2.xml

所以基本上我的主要佈局文件是/res/layout/relative_stuff.xml。我想以編程方式在其中設置兩個表中的任意一個。

回答

5

你和re-use layouts using an include tag

例如,使用例如佈局/ table.xml:

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

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

</LinearLayout> 

如果你不想做它在XML,您可以使用LayoutInflater膨脹您的XML並將其添加到任何容器您正在使用。

LayoutInflater mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); 
View tableLayout = mLayoutInflater.inflate(R.layout.table, (ViewGroup) findViewById(R.layout.root_id)); 
rootLayout.addView(tableLayout); 
+0

謝謝。我會將它添加到我的代碼中,並讓它知道它是否可以在幾分鐘內運行。 – learner 2013-03-14 20:02:35

+0

您也可以使用Activity的['addContentView()'](https://developer.android.com/reference/android/app/Activity.html#addContentView%28android.view.View,%20android.view.ViewGroup.LayoutParams如果合適的話)。 (+1,即使你的第一句話不太正確...) – Sam 2013-03-14 20:04:26

+0

@Tanis是否可以使用包含方法進行網格佈局。如果可能的話,我如何使用Adapter來設置GridLayout的值。 – shanavascet 2014-04-02 19:30:45

0

您可以使用Layout Inflator Service添加多個添加活動。

相關問題