Using lazy loading and avoiding replication Android v1.6+
When you’re creating complex layouts, you may find yourself adding a lot of View- Groups and Views. But making your view hierarchy tree taller will also make it slower. Creating optimized layouts is fundamental to building an application that runs fast and is responsive to the user. In this hack, you’ll learn how to use the <include /> tag in your XML to avoid replication, and how to use the View Stub class to lazy load views.
Avoid replication using the <include /> tag
Let’s imagine we want to add a footer to every view in our application—something simple, such as a TextView with our application’s name. If we have more than one Activity, we might have more than one XML file. Would we copy this TextView to every XML file? What happens if we need to edit it in the future? Copying and pasting would solve the problem, but it doesn’t sound efficient. The easiest way to add a footer to our application is to use the <include /> tag. Let’s look at how it can help us out. We use the <include /> tag in XML to add another layout from another XML file.
In our example, we’ll create our complete view, and at the bottom we’ll add the <include /> tag pointing to our footer’s layout.
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:text="@string/hello"/>
<include layout="@layout/footer_with_layout_properties"/>
</RelativeLayout/>
And the footer_with_layout_properties would look like the following:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="30dp"
android:text="@string/footer_text"/>
In this first example, we’ve used the <include /> tag with the only required layout. You might be thinking, “OK, this works because we’re using a RelativeLayout for our main XML. What’ll happen if one of the XML files is a LinearLayout? android layout_alignParentBottom="true" wouldn’t work because it’s a RelativeLayout attribute.” That’s true. Let’s look at the second way to use includes, where we’ll place android:layout_* attributes in the <include /> itself.