【发布时间】:2010-11-09 09:54:44
【问题描述】:
我在xml(例如Button)中重复了很多控制。有没有可能在xml 中写一次Button,然后在我需要的所有布局中导入它?
【问题讨论】:
-
当我打算制作看起来像 iOS 导航栏的顶部栏时遇到了这个问题。
我在xml(例如Button)中重复了很多控制。有没有可能在xml 中写一次Button,然后在我需要的所有布局中导入它?
【问题讨论】:
你可以使用
<include layout="@layout/commonlayout" android:id="@+id/id" />
commonlayout.xml 应该定义在res/layout 中,您可以在其中添加重复的部分。
【讨论】:
正如 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"
/>
【讨论】:
除了那些出色的答案,您还可以通过使用<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。
【讨论】:
您可以使用默认的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”。
这个库就像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>
【讨论】: