在另一个XML布局文件中包含现有的XML布局文件

3

我在一个名为intro_step1_activity.xml的文件中定义了一个LinearLayout。我希望在另一个xml文件中加载/引用此文件,以便我不需要在其他xml文件中重新输入代码。这是否可能?如果可以,应该如何实现?

4个回答

4

在运行时,您可以使用一个Inflater,例如:

Inflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.intro_step1_activity, null);

然后,您可以将此视图添加到当前视图层次结构中。在编译时,您可以使用xml的include标签。

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

从Android文档: 它永远不会被直接使用。相反,使用getLayoutInflater()或getSystemService(String)来检索标准的LayoutInflater实例,该实例已经连接到当前上下文并正确配置为您正在运行的设备。例如: LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - LightMan

3
Load an existing xml layout file in another xml layout file

要在其他xml文件中使用xml文件,请使用<include />

对于您的intro_step1_activity.xml,使用以下代码:

<include layout="intro_step1_activity.xml"/>

<include layout="@layout/my_layout_file"/> 似乎也可以工作。 - O-9

0
首先给那个LinearLayout一个id,然后在Java中定义一个LinearLayout并使用findViewById()方法引用它。
然后使用刚创建的LinearLayout对象调用addView()方法。
如果需要示例,请留言。

0

是的,可以使用<merge><include>实现。

您可以在这里这里阅读更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接