将多个xml文件合并为一个最终的android布局

lea*_*ner 1 android android-layout

假设我有一个布局文件,我想将其用作另一个布局的一部分,我该怎么做?

例如,我有一个表格布局/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.我想以编程方式在其中设置两个表中的任何一个.

Tan*_*.7x 5

您可以使用include标记重用布局.

例如,使用示例layout/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>
Run Code Online (Sandbox Code Playgroud)

如果您不想在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);
Run Code Online (Sandbox Code Playgroud)