Search code examples
androidiphoneioslayoutsubviews

Re-using Android layouts


On an iphone context, when we add a view as a subview of another view, anything that happens to our subview will be handled correctly, because in the xib we say which class will be handling its actions. How can we achieve this on android? Since we don't have that kind of relation between an .xml layout and a class that uses it, how can we achieve something like that?

The main purpose is, for example: while having one common header and one common footer for the entire application, we just want to add different views to "content View" between the header and footer.


Solution

  • You you can use the layout "include" functionality. This allows you to create a layout file for your header and one for your footer, and then include these layouts into your Activity's main layout. And if you want to include the header + footer in multiple activities and these layouts have some events you want to handle, you could create a BaseActivity that handles these events, and then have your other Activities extend the BaseActivity.

    Example pseudocode:

    title.xml

    <LinearLayout><ImageView/><TextView/></LinearLayout>
    

    footer.xml

    <LinearLayout><TextView/><TextView/></LinearLayout>
    

    main.xml

    <RelativeLayout>
         <include layout="@layout/title"/>
         <WebView />
         <include layout="@layout/footer"/>
    </RelativeLayout>