ViewStub in Android

Abhinay Gupta
2 min readJun 21, 2023

In Android development, `ViewStub` is a lightweight and efficient class that allows you to defer the inflation of a layout resource until it is actually needed. It is typically used when you have a layout component that is initially hidden or not immediately required, but may be needed later on in the application flow.

When you use the `<include>` tag in XML, the layout specified by the included file is inflated immediately, which means it consumes memory and CPU resources even if it is not currently visible. On the other hand, `ViewStub` provides a lazy-loading mechanism where the layout inflation is delayed until the stub is explicitly inflated, thereby conserving system resources.

Here’s an example of how to use `ViewStub` in Android:

First, define the `ViewStub` in your XML layout file:

<LinearLayout

<ViewStub
android:id="@+id/viewStub"
android:layout="@layout/my_inflatable_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Next, in your activity or fragment, you can inflate the `ViewStub` when needed, typically in response to a user action or some other trigger:

val viewStub = findViewById<ViewStub>(R.id.viewStub)
viewStub.inflate()

The `inflate()` method inflates the specified layout resource and replaces the `ViewStub` with the inflated layout, making it visible in the UI.

One important thing to note is that once inflated, the `ViewStub` is replaced by the inflated layout and cannot be used again. If you need to hide the inflated layout and restore the `ViewStub` behavior, you can use the `setVisibility()` method:

viewStub.visibility = View.GONE

This will hide the inflated layout and restore the `ViewStub` to its original state, ready to be inflated again when needed.

To summarize, `ViewStub` provides a way to lazily inflate layout resources in Android, deferring the inflation process until necessary. It helps optimize performance and memory usage by avoiding the immediate allocation of resources for hidden or unused components. In contrast, the `<include>` tag inflates the specified layout immediately, without any deferred inflation mechanism.

--

--