SyntaxHighlighter

Friday, August 27, 2010

Break out your Layout

Recently I faced the issue of needed to reuse a particular layout on multiple screens.  If you are like me you have to copy and paste code.  Anytime I find I need something more than once I look for a way to get some reuse.  Luckily Android has provided a few easy ways to do this when creating your screens.  I'm actually using 2 different ways on my current program.  Take a look at <ViewStub> and <include>, both work very well.
Let’s look at how we can use these in a layout file.
<LinearLayout>
    <!-- The include will load in the layout files -->
    <include android:id="@+id/theStatusBar" layout="@layout/statusbar" />
    <!-- The ViewStub will wait for you to tell them to inflate -->
    <ViewStub android:id="@+id/theView1Stub"
              android:layout_width ="fill_parent"
              android:layout_height="wrap_content"
              android:layout="@layout/view1" />
    <ViewStub android:id="@+id/theView2Stub"
              android:layout_width ="fill_parent"
              android:layout_height="wrap_content"
              android:layout="@layout/view2" >
</LinearLayout>
So in the snippet above, we have two includes and two ViewStubs. The significant difference being the <include> will automatically load in the layout specified and inflate/display it in your Activity’s layout. So when the Activity’s onCreate is called and the setContentView is specified Android will do the magic for you.
Why use <ViewStub> too? Perhaps you need to customize your screen depending on some flag or parameter. Since a ViewStub is not inflated until you tell it, it can be useful. In this example I have a base class that extends from Activity that has the above in its layout file. I also have two other Activity classes that inherit from it. Since the status bar is needed by both screens, the base class can handle loading and controlling that for its children. Each child in its onCreate can then inflate itself once it is started. So in each child class is a line of code to inflate their applicable Viewstub
// inflate ourselves into the layout ViewStub
View view = ((ViewStub) findViewById(R.id.theView1Stub)).inflate();
Check out these online resources here for more info:
Layout Tricks: Creating Reusable UI Components
Layout Tricks: Creating Efficient Layouts
Layout Tricks: Using ViewStubs
Layout Tricks: Merging Layouts

No comments:

Post a Comment