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 thisinflatedId: once inflated, you can refer the view byinflatedId
<ViewStub
android:id="@+id/profileStub"
android:inflatedId="@+id/profileLayout"
android:layout="@layout/fragment_profile_appbar"
android:layout_width="match_parent"
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.VISIBLENOTE: 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.id currentView.visibility = View.VISIBLE}private var currentView: View? = nullif (profileStub != null) { currentView = profileStub.inflate()}loadView(currentView) References:
- https://developer.android.com/training/improving-layouts/loading-ondemand
- https://stackoverflow.com/questions/45904561/how-to-use-kotlin-android-extensions-with-viewstub-properly
- https://stackoverflow.com/questions/44748350/programmatically-inflated-layout-with-kotlin-android-extensions
- https://stackoverflow.com/questions/3334048/android-layout-replacing-a-view-with-another-view-on-run-time