Optimizing Android Layouts
I recently used the hierarchyviewer & lint tool in the Android SDK and was pretty surprised with the results I saw. Many of the views I had were heavily nested and some views did not necessarily have to be inflated off the bat (progress indicators and refresh icons to name a few). As a result, my activity took a performance hit because of a badly designed layout. Here’s a technique I used that I picked up at AnDevCon III to flatten my layouts and in general make them more performant.


Essentially, ViewStub is a lightweight and cheap to inflate widget that you can include in a layout. Its purpose is basically to serve as a stub or placeholder for views that don’t necessarily need to be inflated on creation. For example, let’s say your app displays notifications on a SlidingDrawer; however, when there are no notifications, that SlidingDrawer should be hidden. What you can do then is create a ViewStub that points to your SlidingDrawer layout implementation and when notifications are present, you can simply inflate the ViewStub. Here’s an example taken from Android Developers that displays the flattening of the view hierarchy using ViewStubs. Layout without ViewStub: [caption id=”attachment_341” align=”aligncenter” width=”510”] Layout Without ViewStub[/caption] Layout using ViewStub: [caption id=”attachment_342” align=”aligncenter” width=”468”] Layout With ViewStub[/caption] The code for your layout:
The code to inflate the ViewStub:
ViewStub stub = (ViewStub) findViewById(R.id.stub_slidingdrawer); View v = stub.inflate(); 
For my specific case, it took about half the time to inflate the entire layout tree by using a ViewStub for infrequently used child layouts. Pretty sweet.