Older Post

Re-building Bookmyshow Droidcon Video

Lazy Load Your Views

Lazy Load Your Views

As an Android developer you'r always trying to make your apps more responsive. While there are quite a few things you can do to make your app more responsive, probably one of the oldest and overlooked solution are ViewStubs.

I am pretty sure most of you reading this right now, have never heard of them or used them. I didn't know about them until a couple of years ago either when I ran into a problem of having to build a very complex UI with dynamic elements.

So what is a ViewStub anyway ?

In simple terms, a ViewStub is just a placeholder view with no size/dimension that doesn't draw anything on the screen. Think of it as a stubbed out or a dumb view which can be used to lazily load the layout resource when needed. This can be particularly useful when you have a complex layout or a layout with views required in future(on scroll or based on server response). A ViewStub will speed up the rendering by loading the views only when needed instead of loading all of them at one go in onCreate().

Defining A ViewStub

<ViewStub android:id="@+id/simpleViewStub"  
android:inflatedId="@+id/myInflatedView"  
android:layout="@layout/myViewLayout"  
android:layout_width="fill_parent"  
android:layout_height="wrap_content" />

☝️ It's as simple as that. Just declare a ViewStub element in your layout file and your good to go. As you can see, there is a new attribute :

android:inflatedId="@+id/myInflatedView"  



This is the id the view will take once it is inflated so that you can access it from your Java/Kotlin file. Apart from that, we also provide the actual view layout to be inflated using :

android:layout="@layout/myViewLayout"  


Inflating The View

Now that we have declared our ViewStub, we can now go ahead and inflate it when needed as follows :

val myView: View = findViewById<ViewStub>(R.id.simpleViewStub).inflate()



And there you have it, the view will now be loaded on the screen. The inflate() method is responsible for loading the view declared in the ViewStub. Once you load the view, the ViewStub will no longer be part of the view hierarchy.

Have you used ViewStubs in your projects? If yes, then how often do you use them? Drop in a comment below on the same.