I have lots of control repeated in my xml
(a Button
for instance). Is there any possibility to write the Button
once in a xml
You can use the default include
XML tag to include an external layout:
<include layout="@layout/somelayout" />
This layout should have an outside ViewGroup
that encapsulates the content or a merge
tag to avoid having to use an unnecessary layout:
<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>
Also, if you need a better way to include pieces of layout that acts like a container (a custom ViewGroup
), you can use this custom ViewGroup. Note that this does not import an XML into another XML file, it inflates the content from the external layout and replaces into the view. It's similar to ViewStub
, a "ViewGroupStub" like.
This lib acts as if the ViewStub
could be used as following (note that this example does not work! ViewStub
isn't a ViewGroup
subclass!):
<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>
As Labeeb P rightly said, it works. Just want to add that you can also override parameters too:
<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"
/>
You can use
<include layout="@layout/commonlayout" android:id="@+id/id" />
commonlayout.xml
should be defined in res/layout
where you can add the repeated parts.
In addition to those great answers, you can also avoid code duplication by using the <merge>
tag, like so:
<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>
The <merge>
part gets stripped when you include it into other xml. This might help including more than a single Button
at a time. See the official documentation.