将XML导入另一个XML

48

我在我的xml中有许多重复的控件(例如Button)。是否有可能只在一个xml文件中写一次Button,然后在需要它的所有布局中导入它?


当我要创建类似于iOS导航栏的顶部条时,我遇到了这个问题。 - Castor
4个回答

112

你可以使用

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

commonlayout.xml 应该定义在 res/layout 中,您可以在其中添加重复的部分。


26

正如 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"
 />

4
除了以上这些好的答案,您还可以通过使用<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。请参见官方文档了解更多信息。

1
你可以使用默认的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)的布局片段,可以使用这个 自定义ViewGroup。请注意,这不会将 XML 导入到另一个 XML 文件中,而是将内容从外部布局填充并替换到视图中。它类似于 ViewStub,就像“ViewGroupStub”一样。
此库的作用就像 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>

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