Android Dynamically Load (On Demand) View With ViewStub (Kotlin)

If you have multime views which you would like to load them on demand programatically, ViewStub is one of the solution.

Sometimes your layout might require complex views that are rarely used. Whether they are item details, progress indicators, or undo messages, you can reduce memory usage and speed up rendering by loading the views only when they are needed.

ViewStub is a lightweight view with no dimension that doesn’t draw anything or participate in the layout. As such, it's cheap to inflate and cheap to leave in a view hierarchy.

Define a ViewStub.

  • layout: layout file for this
  • inflatedId: once inflated, you can refer the view by inflatedId
    android:layout_height="wrap_content" />

You can load/inflate the stub by calling inflate() or set it visible.

val view = profileStub.inflate()// orprofileStub.visibility = View.VISIBLE

NOTE: Once ViewStub is loaded/inflated, the ViewStub become null and replaced by the View with inflatedId

If you have multiple StubView, and you want only one of them to be visible at anytime.

private var lastViewId: Int? = nullfun loadView(currentView: View) {    lastViewId?.let {        val view = findViewById<View>(it)        view.visibility = View.GONE    }    lastViewId =    currentView.visibility = View.VISIBLE}
private var currentView: View? = nullif (profileStub != null) {    currentView = profileStub.inflate()}loadView(currentView) 


❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.