Include-Merge Example in Android

This example will explain how to reuse the same layouts which is used in many layout files such as the footer used on each screen in many applications. We can do this by using include and merge tags. It basically means that include tag takes that file and paste it’s contents here. The include tag as the name suggests is more like the one in JSP, HTML or other languages. It takes another layout and includes that in the current layout.

Merge tag explains The layout which we have to use must be enclosed under merge tag, so that we can include layouts from other xml. The tag was created for the purpose of optimizing Android layouts by reducing the number of levels in view trees. Use the merge tag instead of linearLayout as a root tag around your layout elements if you are going to include that in another layout.

Rewriting the same code in each xml file will consume much more time and reduce the efficiency of the application.
Also reusing code will make the code clean, easier to understand and hence easy to debug.

Let us see how include tag works. For example we have the following header.xml file to use as a header in every screen .




The tag is used for the purpose of optimizing Android layouts by reducing the number of levels in view trees.

Suppose we want to include the above header file as a header in homescreen file of our application which displays a list of games. We can do it as follows




Now we can take the references of the views used in header.xml by calling the method findViewById(int id) in the activity inflating the homescreen.xml and do whatever we want.

In this example we are going to use both include and merge tags to generate our complete layout. We have created the footer layout with merge tags as it will be used throughout the application and can be included in all pages. I

1.) Create and write following into footer.xml:




2.) Write following into main.xml:




3.) Write following into MainActivity class: